0
|
6229 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
GROUPS:

# How to pair corresponding elements in a list?

Posted 12 years ago
 It's tough to explain what I want to do in words, so I'll explain with examples. What is the easiest way to create a function that does the following:in[1]: function[{{a1, b1},{a2, b2}}]out[1]: {{a1, a2}, {b1, b2}}in[2]: function[{a1, b1, c1, d1}, {a2, b2, c2, d2}]out[2]: {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}in[3]: function[{{a1, b1},{a2,b2},{a3,b3}}]out[3]: {{a1, a2, a3}, {b1, b2, b3}}Essentially I want to group the corrisponding elements of the seperate sublists, to create a new set of sublists.Any help is greatly appreciated.
3 Replies
Sort By:
Posted 12 years ago
 Transpose does exactly what you want:In[14]:= Transpose[{{a1, b1}, {a2, b2}}]Transpose[{{a1, b1, c1, d1}, {a2, b2, c2, d2}}]Transpose[{{a1, b1}, {a2, b2}, {a3, b3}}]Out[14]= {{a1, a2}, {b1, b2}}Out[15]= {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}Out[16]= {{a1, a2, a3}, {b1, b2, b3}}
Posted 12 years ago
 MapThread is a very good choice for generalized operations, when you not only pairing but also applying a function to pairs. In your simpler case you can also use Thread and Transpose (see blow). Relations between MapThread, Thread, and Transpose are discussed here. In[1]:= Transpose[{{a1, b1}, {a2, b2}, {a3, b3}}] Out[1]= {{a1, a2, a3}, {b1, b2, b3}}  In[2]:= Thread[{{a1, b1}, {a2, b2}, {a3, b3}}] Out[2]= {{a1, a2, a3}, {b1, b2, b3}}  In[3]:= Transpose[{{a1, b1, c1, d1}, {a2, b2, c2, d2}}] Out[3]= {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} In[4]:= Thread[{{a1, b1, c1, d1}, {a2, b2, c2, d2}}]Out[4]= {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}In[5]:= MapThread[List, {{a, b, c}, {x, y, z}}]Out[5]= {{a, x}, {b, y}, {c, z}}
Posted 12 years ago