Multiple assignment between lists in Mathematica 7

Suppose there are two lists a = {a1, a2, a3} and b = {b1, b2, b3} , and I want to write an assignment operator to make a1=b1,a2=b2,a3=b3 , which only applies to a and b :

 Thread[a = b] 

But this only does a={b1,b2,b3} . Usage := (SetDelayed) instead of = doesn't work either.
Any solution? Thanks.

+4
source share
4 answers

I think Thread only works with "explicit" lists; variables must be expanded before they work.

After some experimentation, this works for me:

  a = {a1, a2, a3};
 b = {b1, b2, b3};
 Thread [Set [ Evaluate@a , Evaluate@b ]];
 {a1, a2, a3}

You can also write Thread[ Evaluate@a = Evaluate@b ] ; just depends on what you find more readable.

+5
source

what happened with

MapThread [Install, {{a1, a2, a3}, {b1, b2, b3}}]

?

+2
source

Here's another solution:

 a = {a1, a2, a3}; b = {b1, b2, b3}; each[{x_, y_}, Transpose[{a, b}], x = y] 

which uses my handy function each :

 SetAttributes[each, HoldAll]; (* each[pattern, list, body] *) each[pat_, lst_, bod_] := (* converts pattern to body for *) Scan[Replace[#, pat:>bod]&, Evaluate@lst ] (* each element of list. *) 

Similarly, you can do this:

 MapThread[(#1 = #2)&, {a, b}] 
+1
source

Well, if they are really called a1 , a2 , etc., you can do this:

 Assign[x_, y_] := Module[{s1, s2, n, sn}, s1 = SymbolName[Unevaluated[x]]; s2 = SymbolName[Unevaluated[y]]; For[n = 1, n <= Length[x] && n <= Length[y], n++, sn = ToString[n]; Evaluate[Symbol[s1 <> sn]] = Evaluate[Symbol[s2 <> sn]] ] ] SetAttributes[Assign, HoldAll] 

And then

 Clear[b1, b2, b3]; Clear[a1, a2, a3]; a = {a1, a2, a3} b = {b1, b2, b3} Assign[a, b] a 

Gives results for a , b and a again as:

 {a1, a2, a3} {b1, b2, b3} {b1, b2, b3} 

As expected.

In general, you can create expressions like these from the correct use of SymbolName and Symbol , but be careful when evaluating. If I wrote SymbolName[x] (without Unevaluated ), he would interpret it as SymbolName[{a1, a2, a3}] , which is clearly undesirable. Without using Evaluate on Symbol[s1 <> sn] , Mathematica will report that you are trying to reassign the Symbol function.

0
source

All Articles