I was trying to create a list of n
variables such as x = Table[Symbol["x" <> ToString[i]], {i, 5}]
, which be done by using Symbol
. However, if after that, I want to assign values to those variables, I could not figure out how to properly reference a variable using x
and an index (I prefer this method because I may need to reference the variables in a loop). For example, in the code that follows, x[[1]] = 5
does not assign the value to x1
. How could I reference x1
properly using x
and an index?
1 Answer
While I would suggest indexing using arguments (x[1], x[2], ...
), you can simply add Evaluate
on the lhs of the assignment as
x = Table[Symbol["x" <> ToString[i]], {i, 5}]
Evaluate@x[[1]] = 5
x
x1
{x1, x2, x3, x4, x5}
5
{5, x2, x3, x4, x5}
5
x[1]
,x[2]
, etc. as variables? (afterClear[x]
I mean). I think making a list of variables and then trying to refer to them is needlessly complicated. $\endgroup$x[1], x[2], ...
and then assign them values, it is essentially defininga functionx
with some discrete values, right? $\endgroup$x
. $\endgroup$