5
$\begingroup$

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?

$\endgroup$
  • 4
    $\begingroup$ ls = {w0, w1, w2}; v = {0.1, 0.2, 0.3}; Evaluate@ls = v $\endgroup$ – Apple Jun 24 '14 at 11:16
11
$\begingroup$

Use MapThread

MapThread[Set, {ls, v}]
$\endgroup$
2
$\begingroup$

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

$\endgroup$
0
$\begingroup$

Inner works here! (MapThread is more general, but requires List wrapping)

Inner[Set, ls, v]
$\endgroup$
-1
$\begingroup$

I would try with

ToExpression[" ls[[1]]  = v[[1]] " ];
$\endgroup$
  • $\begingroup$ This does not give a value to w0, it just changes the value of ls[[1]] $\endgroup$ – Jason B. Mar 2 '16 at 11:56

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