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?
Asked
Active
Viewed 2,204 times
8
LCarvalho
- 9,233
- 4
- 40
- 96
Ferran Mazzanti
- 81
- 2
-
4ls = {w0, w1, w2}; v = {0.1, 0.2, 0.3}; Evaluate@ls = v – Apple Jun 24 '14 at 11:16
4 Answers
2
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
Jason B.
- 68,381
- 3
- 139
- 286
0
Inner works here! (MapThread is more general, but requires List wrapping)
Inner[Set, ls, v]
Aisamu
- 2,618
- 14
- 17
-1
I would try with
ToExpression[" ls[[1]] = v[[1]] " ];
Karsten7
- 27,448
- 5
- 73
- 134
-
This does not give a value to
w0, it just changes the value ofls[[1]]– Jason B. Mar 02 '16 at 11:56