1
$\begingroup$

I want to get $\{x_1, x_2, \cdots, x_n\}$.
I want to use the $x_i$ as a variable.
The following code did't work.

getVectorX[n_]:=Table[Subscript[x, i], {i, 1, n}]
x = getVectorX[5]
$\endgroup$
  • 4
    $\begingroup$ if you need indexed variables it is better suggested to use x[i] instead of Subscript[x,i] $\endgroup$ – user42582 Sep 21 '18 at 8:44
  • $\begingroup$ Thank you very much, user42582 for your advice. $\endgroup$ – tchappy ha Sep 21 '18 at 9:23
  • $\begingroup$ $x[1] = 1$, $x = 2$, Then $x[1]$ returns $2[1]$. But I want to use $x[1]$ as a variable independent to $x$. $\endgroup$ – tchappy ha Sep 21 '18 at 9:28
  • $\begingroup$ Array[Subscript[x, #] &, 10] but, as user42582 points out, indexed variables can cause problems (this is my experience). Maybe consider Array[x[#] &, 10]?. $\endgroup$ – user1066 Sep 21 '18 at 10:08
  • $\begingroup$ @tchappyha you need to decide what symbol you are going to use for you variables eg x and then you should use a different symbol for the the list of variables you are going to create; using x for the variables (eg x[1]) and the list of generated variables (eg x = {x[1], x[2],...}) causes infinite recursion; you could write something like eg y = {x[1], x[2], x[3]}. $\endgroup$ – user42582 Sep 21 '18 at 11:22
2
$\begingroup$

It raises an error because x appears at both the right- and left-hand sides of your last expression. Try renaming one side instead, for example

xVec = getVectorX[5]

BTW, Indexed can replace Subscript here.

$\endgroup$
  • $\begingroup$ Thank you very much. $\endgroup$ – tchappy ha Sep 21 '18 at 9:21
2
$\begingroup$

There is no reason for the subscripted variable to be a symbol. Just use a string instead, and you won't have to worry about recursion errors because the subscripted variable is the same as the variable on the LHS:

getVectorX[n_] := Table[Subscript["x", i], {i, 1, n}]
x = getVectorX[5];
x //TeXForm

$\left\{\text{x}_1,\text{x}_2,\text{x}_3,\text{x}_4,\text{x}_5\right\}$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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