2
$\begingroup$

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?

enter image description here

$\endgroup$
3
  • 4
    $\begingroup$ How about just using x[1], x[2], etc. as variables? (after Clear[x] I mean). I think making a list of variables and then trying to refer to them is needlessly complicated. $\endgroup$
    – Roman
    Jan 29, 2020 at 21:27
  • $\begingroup$ @Roman Good point. By using x[1], x[2], ... and then assign them values, it is essentially defininga function x with some discrete values, right? $\endgroup$
    – nanjun
    Jan 29, 2020 at 21:36
  • 1
    $\begingroup$ Colloquially speaking, yes. Strictly speaking, there are no functions in Mathematica, and you're assigning DownValues to the symbol x. $\endgroup$
    – Roman
    Jan 29, 2020 at 21:43

1 Answer 1

3
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.