Lets say I have a list of undefined variables {a1,a2,a3,a4}. I could type out each element by hand, but if I wanted to eventually extend the list, it would be easier generate the list by Table[ToExpression["a" <> ToString[i]], {i, 1, 4}].

Now, lets say I want to assign values to each element. In the first method when I type it out by hand, I simply put {a1,a2,a3,a4} = {1,2,3,4}, then I get the result that I wanted: a1=1, a2=2, a3=3, a4=4.

Now, if I try to assign to each element a value using the second method, I would think it would make sense to put Table[ToExpression["a" <> ToString[i]], {i, 1, 4}] = {1,2,3,4}. However, it gives me an error.

How can I equate a variable list generated by the table function to another list? I have tried about 5 different methods, and the only thing that seems to work is to copy and paste the output from the table function into a new kernel, but this is not an elegant solution at all.

  • 1
    $\begingroup$ Are you sure Indexed cannot meet your needs? $\endgroup$
    – Alan
    Commented Dec 30, 2017 at 14:07

1 Answer 1

Evaluate[Table[ToExpression["a" <> ToString[i]], {i, 1, 4}]] = {1, 2, 3, 4}

You need to ensure that the first argument of Set (=) is actually evaluated, because Table is protected, but it will handle List as expected once Table is evaluated.

  • $\begingroup$ thank you so much! $\endgroup$
    – ngc1300
    Commented Dec 30, 2017 at 5:22

Your Answer

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

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