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!
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.
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_] := ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With