Table of Variables

16

7

I use a list of variables {x1, x2, x3} to Solve a particular set of equations.

I am now trying to generalise this depending on the number of equations.

I need something along the lines of Table[{"x" i}, {i,1,Length[equations]}] which prints {x1, x2, x3, x4,...} etc.

However, "x" i obviously does not work. Nor does x[[i]] as {x[[1]], x[[2]], x[[3]]} won't work in Solve.

Any quick thoughts?

Thank you.

LBogaardt

Posted 2013-11-12T14:52:14.503

Reputation: 1 495

Closely related, perhaps duplicate?: (6623), (20160)

– Mr.Wizard – 2017-02-15T15:13:42.173

Answers

17

Use Symbol to convert a string into a symbol...

Table[Symbol["$x" <> ToString@i], {i, 5}]

{$x1, $x2, $x3, $x4, $x5}

One word of caution. I tend to keep programmatically generated variables prepended with a $ to avoid any collisions with any other variables I might've defined. Just from experience.

kale

Posted 2013-11-12T14:52:14.503

Reputation: 10 290

1Perfect! Thanks! – LBogaardt – 2013-11-12T16:49:06.557

1Unique can also be helpful. – ybeltukov – 2013-11-12T16:52:19.070

I admit I also use leading $ for variable names but I think it is important to reminde people that this has the danger to conflict with Module local variable names, especially when they end -- as in this case -- with digits... – Albert Retey – 2013-11-13T13:36:02.680

Is it possible to use this within a Control environment, in a Manipulate? I tried it, but it doesn't seem to work. Somehow Control[{{a1, 0, ""}, {1, 0}}] is not the same as Control[{{Symbol["$a" <> ToString@1], 0, ""}, {1, 0}}]. Any idea how to fix this? – sam wolfe – 2020-03-02T15:14:42.013

19

You almost have found a simple solution: try x[i] instead of x[[i]]

Solve[{x[1] + x[2] == 2, x[1] - x[2] == 1}, {x[1], x[2]}]

{{x[1] -> 3/2, x[2] -> 1/2}}

List of this variables:

Array[x,2]

{x[1], x[2]}

ybeltukov

Posted 2013-11-12T14:52:14.503

Reputation: 41 907

So close :P Thanks! – LBogaardt – 2013-11-12T16:49:24.103

2I actually think that this is in a lot of cases the better solution: it is much easier to access these variables in a programmatic way and many functions as Solve, NDSolve,... do accept "nonatomic" variable names, so at least for them it isn't necessary to create those symbols programmatically... – Albert Retey – 2013-11-13T13:39:19.083

1

Or you could make a function to add a range of numbers to a predefined string("x")

f2 := Function[{i}, ToExpression["x" <> ToString[#]] & /@ Range[i]]

f2[5]

{x1,x2,x3,x4,x5}

Or a function to add a range of numbers to any string

f3 := Function[{i, s}, ToExpression[s <> ToString[#]] & /@ Range[i]]

f3[5, "y"]

{y1,y2,y3,y4,y5}

ps1

Posted 2013-11-12T14:52:14.503

Reputation: 71