# List operations: how to combine two lists (pattern given)?

Two lists (matrixes) are given:

a = {{x1, y1}, {x2, y2}, {x3, y3}};
b = {{u1, v1}, {u2, v2}, {u3, v3}};


Expected return:

c = {{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}


Please, help to solve this. Useful references are also welcome.

duplicates

• Have a look at ArrayFlatten[] or MapThread[] and Transpose[]. Commented May 26, 2015 at 16:24

a = {{x1, y1}, {x2, y2}, {x3, y3}};
b = {{u1, v1}, {u2, v2}, {u3, v3}};


The output is

{{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}

• even shorter: MapThread[List, {a, b}, 2]
– chuy
Commented May 26, 2015 at 16:29
• Even harder to read: Transpose@{#1,#2}&@@@Transpose@{a,b} :) Commented May 26, 2015 at 16:34
• My fault not to think and search carefully before asking. Nice general way: SetAttributes[add, Listable]; add[x_,y_]:={x,y} Commented May 26, 2015 at 19:52
a = {{x1, y1}, {x2, y2}, {x3, y3}};
b = {{u1, v1}, {u2, v2}, {u3, v3}};
c = {{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}

res = Thread[{a, b}] // Transpose[#, {1, 3, 2}] &

MatrixForm /@ {a, b, c, res}


a = {{x1, y1}, {x2, y2}, {x3, y3}};
b = {{u1, v1}, {u2, v2}, {u3, v3}};

Transpose /@ Transpose[{a, b}]


{{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}

As of Version 13.1+, we could use Threaded like so:

a = {{x1, y1}, {x2, y2}, {x3, y3}};
b = {{u1, v1}, {u2, v2}, {u3, v3}};

combine = Function[{e1, e2}, {e1, e2}, Listable];

a ~ combine ~ Threaded @ b

(* {{{x1,u1},{y1,v1}},{{x2,u2},{y2,v2}},{{x3,u3},{y3,v3}}} *)


But in this case it isn’t even needed as we are operating at the lowest level for two lists having the same dimensions:

a ~ combine ~ b

• Of course, combine[ a, Threaded[b] ] is equivalent.
– gwr
Commented Feb 22 at 11:25
Transpose[{a, b}, {3, 1, 2}]


{{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}

Map[Variables,Partition[Flatten[a]*Flatten[b], 1]]


outputs

{{u1,x1}, {v1,y1}, {u2,x2}, {v2,y2}, {u3,x3}, {v3,y3}}


The Documentation Center is a great resource.

• Thank U, I've noticed that DC has a direct solution to my 'problem'. BTW, output is not exactly as expected. Commented May 27, 2015 at 5:53
a = {{x1, y1}, {x2, y2}, {x3, y3}};
b = {{u1, v1}, {u2, v2}, {u3, v3}};


Using Riffle, Partition and Thread:

Thread /@ Partition[Riffle[a, b], 2]

(*{{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}*)


Or using Table, Partition and Riffle:

Table[Partition[Riffle[a[[i]], b[[i]]], {2}], {i, #}] &@ Max@Dimensions@{a, b}

(*{{{x1, u1}, {y1, v1}}, {{x2, u2}, {y2, v2}}, {{x3, u3}, {y3, v3}}}*)