3
$\begingroup$

Let me preface this question by noting that this is a simple example meant to clarify what I am asking. The actual context in which I want to implement this involves associations containing hundreds of variables, nested for loops, and writing to/reading from files. Because of this, the traditional method of setting a list of variables to a list of values (e.g. {a,b,c}={1,2,3}) is not practical.

Here is my simplified example:

Suppose I have a list of variables which have already been defined: a,b,c,d,e,f. I want to set these variables to values of 1,2,3,4,5,6 using a for loop.

To do this, I define the list:

listOfVar = {"a","b","c","d","e","f"}

And naively use the following for loop

For[i=1,i<=listOfVar,i++,
  listOfVar[[i]] = i
]

Clearly, this won't work, as it will just set

listOfVar = {1,2,3,4,5}

My question is thus:

How do I replace listOfVar[[i]] with the variable name which its string represents? (e.g. how do I replace listOfVar[[3]] with the variable c so that the for loop correctly sets c to the value of 3?)

I have tried many combinations of Hold[],ToExpression[],ToString[],etc., but I do not seem to have enough knowledge of the low-level operations of Mathematica to solve this problem (or perhaps I am overlooking an obvious solution for whatever reason). I would greatly appreciate the help, as this is a problem I have given up on multiple times.

$\endgroup$
0

2 Answers 2

5
$\begingroup$
listOfVar = {"a", "b", "c", "d", "e", "f"};
ClearAll @@ listOfVar;
Do[
 ToExpression[listOfVar[[i]], InputForm, Set[#, i] &], 
 {i, 1, Length[listOfVar]}
 ];
Symbol /@ listOfVar

{1, 2, 3, 4, 5, 6}

$\endgroup$
1
  • 1
    $\begingroup$ Notice that Set[#, i] & does not hold its arguments. So if a has value it will break. $\endgroup$
    – Kuba
    Commented Feb 24, 2019 at 13:58
1
$\begingroup$

Here is a second answer, if anyone is curious. It is a modification of an answer to another question I found after searching for an hour or two.

ClearAll @@ listOfVar;
  For[i = 1, i <= Length[listOfVar], i++,
  Evaluate[Symbol[listOfSavedVariables[[i]]]] = i;
]
$\endgroup$
1
  • 2
    $\begingroup$ It will work only once. If a e.g. has any value it will fail. $\endgroup$
    – Kuba
    Commented Feb 24, 2019 at 13:58

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