How to save multiple variables with an iterated name in Mathematica?

I want to create several 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, ... etc.

I error:

Set :: write: The StringJoin tag in f <> 1 is protected. →

Any help would be great. Thanks!

+4
source share
2 answers

To achieve this, you need to evaluate the expression "f" <> ToString[i] before Set ( = ) sees it, or you try to assign an object with a StringJoin head as soon as an error message tries to tell you. In addition, you cannot assign a string, so you need to convert it to 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 usually not a good course of action with Mathematica. For example, if any of these characters already exists and has an assigned value, the operation will fail. You can get around this with great effort, as shown in the answers to How to block characters without evaluating them? (or, more specifically, in my answer here ), but then again, this is usually not a good course of action.

The usual method is to use indexed objects , as PrinceBilliard shows.

See this question , its answers, and four related questions related in the comment below for more details on this topic as a whole.

+4
source

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

Iterable variable names work like f [i]. You can also declare iterated function names, for example f[2][x_] := ...

+2
source

All Articles