Search code examples
nestedcoordinateswolfram-mathematicatransposenested-lists

Mathematica: How do make a nested list of x coordinates and a nested list of y coordinates into a nested list of (x,y) coordinates?


I have two nested lists: one with a set of "a through d" nested x coordinates, and one with a set of "a through d" nested y coordinates.

    xlist={{xa1,xa2,xa3,xa4},{xb1,xb2,xb3,xb4},{xc1,xc2,xc3,xc4}}
    ylist={{ya1,ya2,ya3,ya4},{yb1,yb2,yb3,yb4},{yc1,yc2,yc3,yc4}}

How can I make a nested list of coordinates in the following format? final={{{xa1,ya1},{xa2,ya2},{xa3,ya3},{xa4,ya4}},{{xb1,yb1},{xb2,yb2},{xb3,yb3},{xb4,yb4}},{{xc1,yc1},{xc2,yc2},{xc3,yc3},{xc4,yc4}},{{xd1,yd1},{xd2,yd2},{xd3,yd3},{xd4,yd4}}}

I have successfully used the following to accomplish what I want on the first element only, but I am brand new to Mathematica and don't know how to create a list that does this to all elements.

Transpose[{xlist[[1]], ylist[[1]]}]

Thanks so much for your help!


Solution

  • This

    xlist={{xa1,xa2,xa3,xa4},{xb1,xb2,xb3,xb4},{xc1,xc2,xc3,xc4}};
    ylist={{ya1,ya2,ya3,ya4},{yb1,yb2,yb3,yb4},{yc1,yc2,yc3,yc4}};
    h[p_,q_]:=Transpose[{p,q}];
    final=MapThread[h,{xlist,ylist}]
    

    instantly returns

    {{{xa1,ya1},{xa2,ya2},{xa3,ya3},{xa4,ya4}},
     {{xb1,yb1},{xb2,yb2},{xb3,yb3},{xb4,yb4}}, 
     {{xc1,yc1},{xc2,yc2},{xc3,yc3},{xc4,yc4}}}
    

    which matches your desired output exactly except I don't know where your

     {{xd1,yd1},{xd2,yd2},{xd3,yd3},{xd4,yd4}}
    

    was supposed to come from given your input. I assume that was a typo.

    As always with Mathematica, there are almost certainly other ways of doing this. Pick one that you can remember and use without making too many mistakes.

    Another way you could do this is

    final=MapThread[Transpose[{#1,#2}]&,{xlist,ylist}]
    

    which produces exactly the same result

    Another way you could do this is

    final=Table[Transpose[{xlist[[i]],ylist[[i]]}],{i,1,3}]
    

    which produces exactly the same result

    Another way you could do this is

    final=Partition[Transpose[{Flatten[xlist],Flatten[ylist]}],4]
    

    which produces exactly the same result

    There must be more ways than this to do this

    Check each of these carefully to make certain I've made no mistakes