I hope somebody can help me in this (I guess) simple question: I have a list of variable names
ls={w0,w1,w2}
and another list of values
v={0.1,0.2,0.3}
What I'd like to do is to get the names of the variables from ls and assign to these variables the values in v, that is, to end up with variables w0,w1 and w2 that have the values 0.1
, 0.2
and 0.3
. I've tried things like
ToExpression[ls[[1]]] =ToExpression[v[[1]]]
but I keep getting messages of the form
Set::write: Tag ToExpression in ToExpression[ω0] is Protected.
>>
Can anybody tell me of a simple way to achieve what I'm looking for?
-
4$\begingroup$ ls = {w0, w1, w2}; v = {0.1, 0.2, 0.3}; Evaluate@ls = v $\endgroup$– AppleJun 24, 2014 at 11:16
4 Answers
I like molekyla777's answer the best, but another way to do it is via Evaluate
. Initializing,
ClearAll[w0, w1, w2, v, ls];
ls = {w0, w1, w2};
v = {0.1, 0.2, 0.3};
This will pass the assignments onto the symbols inside of ls
,
Evaluate[ls] = v;
{w0, w1, w2}
(* {0.1, 0.2, 0.3} *)
The reason this works is that Set
has the attribute HoldFirst
, so if we tried ls=v
, then the ls
is not evaluated to be {w0, w1, w2}
. Using Evaluate
removes the Hold
Inner
works here! (MapThread
is more general, but requires List wrapping)
Inner[Set, ls, v]
I would try with
ToExpression[" ls[[1]] = v[[1]] " ];
-
$\begingroup$ This does not give a value to
w0
, it just changes the value ofls[[1]]
$\endgroup$– Jason B.Mar 2, 2016 at 11:56