Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
    
Perfect! Thanks! –  LBogaardt Nov 12 '13 at 16:49
    
Unique can also be helpful. –  ybeltukov Nov 12 '13 at 16:52
    
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 Nov 13 '13 at 13:36
add comment

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]}

share|improve this answer
    
So close :P Thanks! –  LBogaardt Nov 12 '13 at 16:49
    
I 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 Nov 13 '13 at 13:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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