Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save multiple variables with an iterated name in Mathematica?

I want to create multiple variables with iterated names in Mathematica, something like this:

Do["f" <> ToString[i] = i*2, {i, 1, 20}]

where I get f1=2, f2=4, f3=6, ... and so on.

I the error:

Set::write: Tag StringJoin in f<>1 is Protected. >>

Any help would be great. Thanks!

like image 669
tquarton Avatar asked Aug 02 '12 18:08

tquarton


Video Answer


2 Answers

To achieve this you need to evaluate the "f" <> ToString[i] expression before Set (=) sees it, or you attempt to assign to an object with head StringJoin, just as the error message tries to tell you. Further, you cannot make an assignment to a string, so you need to convert it to a Symbol, using (surprise) Symbol. One method is to use Evaluate:

Do[Evaluate[Symbol["f" <> ToString[i]]] = i*2, {i, 1, 20}]

{f1, f2, f17}

{2, 4, 34}

This however is not usually a good course of action with Mathematica. For example, if any of these symbols already exist and have a value assigned the operation will fail. One can get around this with more effort as seen in the answers to How to Block Symbols without evaluating them? (or more specifically in my answer here) but again, it is not usually a good course of action.

The normal method is to use indexed objects as PrinceBilliard shows.

Please see this question, its answers, and the four related questions linked in the comment below it for more on this topic in general.

like image 149
Mr.Wizard Avatar answered Oct 29 '22 15:10

Mr.Wizard


Do[f[i] = i^2, {i,1,20}]

Iterated variable names work like f[i]. You can also declare iterated function names, such as f[2][x_] := ...

like image 28
PrinceBilliard Avatar answered Oct 29 '22 16:10

PrinceBilliard