Search code examples
wolfram-mathematica

Create variable names in loop


My aim is to create a lot of functions f_i in a loop. These functions depend on parameters a[[i]], which can be taken from array A = {a1, a2, ...}. In order to eliminate the influence of the interator i, which leads to the situation when all functions are the same, I aspire to create variable names for each iteration.

The example: suppose I have got the array W = {1,2,3, ..., 100} and I should create variables w1 = 1, w2 = 2, ..., w100 = 100. I am trying to do this with the help of a for-loop:

loc[expr1_, expr2_] := 
  ToExpression[StringJoin[ToString[expr1], ToString[expr2]]];
For[i = 1, i <= 100, i++, 
{
loc[w, i] = W[[i]];
}]

When I need to see which value variable wk contains, then wk is not defined. But loc[w, k] = k is known. How can I define variables wi? Or is there another way to create functions in a loop? Thanks in advance


Solution

  • The way you are using {} leads me to believe that you have prior experience with other programming languages.

    Mathematica is a very different language and some of what you know and expect will be wrong. Mathematica only uses {} to mean that is a list of elements. It is not used to group blocks of code. ; is more often used to group blocks of code.

    Next, try

    W={1,2,3};
    For[i=i,i<=3,i++,
       ToExpression["w"<>ToString[i]<>"="<>ToString[i]]
    ];
    w2
    

    and see that that returns

    2
    

    I understand that there is an intense desire in people who have been trained in other programming languages to use For to accomplish things. There are other ways o doing that for most purposes in Mathematica.

    For one simple example

    W={1,2,3};
    Map[ToExpression["z"<>ToString[#]<>"="<>ToString[#]]&,W];
    z2
    

    returns

    2
    

    where I used z instead of w just to be certain that it wasn't showing me a prior cached value of w2

    You can even do things like

    W={1,2,3};
    loc[n_,v_]:=ToExpression[ToString[n]<>ToString[v]<>"="<>ToString[v]];
    Map[loc[a,#]&,W];
    a3
    

    which returns

    3