I would like to set values to a list of variables, like so:
list[[1]] = 2
and if list[[1]]
is a
, then a
will now be equal to two. How can I achieve this?
I would like to set values to a list of variables, like so:
list[[1]] = 2
and if list[[1]]
is a
, then a
will now be equal to two. How can I achieve this?
What you request is generally hard in Mathematica, since it is hard to imitate the pointer semantics. The following code will do specifically what you asked for, but is restricted to only symbols as list elements:
Examples:
I just had a similar problem with defining the value of symbols, when you first dont know wich symbol you want to redefine. Your answers helped me to find the right way doing that:
HoldPattern worked very well for me here, even if values have been allready set for variables.
So my solution is pretty much like the first solution by Sjoerd C. de Vries, but it protects the symbols from being evaluated inside of the list by HoldPattern.
Note, that one has to use ReleaseHold to use the list for further calculations. The variables (a,b,c,d) dont get affected by this construction.
This was my first post here, hope you like it ;-)
Well, let's try it naively:
Make a list:
It's as we expect it:
Set the first element to 2:
That doesn't affect a:
Start again:
The problem is that Set (=) has
HoldFirst
as one of its attributes , i.e., it doesn't evaluate its first argument which is the lefthand side, and the assignment is to the list and not to the variable that's in that location. But you can force evaluation usingEvaluate
:Now the list seems to be the same as before:
but that's only because a is still there and has gotten the value of 2 (in the previous version a was replaced by 2):
If you now set a to 3 you'll see that that changes list too:
EDIT
Perhaps more close to the wording of your question, you could
Map
Set
over the list:You could perhaps do:
Though that may be a bit hackish. The correct way is by playing around with how values are Held from being evaluated, but I couldn't remember how; see other answers.