# Create a Matrix out of two matrices

I have two matrices A = {{a1,a2},{b1,b2}} and B = {{x1,x2},{y1,y2}}. I would like to create out of these matrices a new matrix C={{{a1,x1},{a2,x2}},{{b1,y1},{b2,y2}}} which I would like at the end transform to this form {{a1,x1},{a2,x2},{b1,y1},{b2,y2}}. Of course, I am looking for a solution to the general case. Thanks.

• I have a problem when B is a vector not a matrix, both procedures below do not work. Is there a way around it? – Friedrich Nietzsche Jul 20 '13 at 20:12

With

a = {{a1, a2}, {b1, b2}}; b = {{x1, x2}, {y1,  y2}};


Then

Transpose[{Flatten[a], Flatten[b]}]

{{a1, x1}, {a2, x2}, {b1, y1}, {b2, y2}}


gives you the form you want.

• Thanks; simple and to the point! – Friedrich Nietzsche Jul 14 '13 at 21:23
• I have problem when b={x,y}; the procedure that you suggested does not work. Is there any way around it? – Friedrich Nietzsche Jul 20 '13 at 20:13
• If a is a matrix and b is a vector, what do you want the answer to be? – bill s Jul 20 '13 at 20:16
• Suppose a = {{a1, a2}, {b1, b2}}; b = {x, y}; I want to obtain {{a1, a2,x}, {b1, b2,y}}. Thanks. – Friedrich Nietzsche Jul 20 '13 at 20:22
• Probably not too generalizable, but Partition[Flatten[Riffle[a, b]], 3] gives you the answer you want. – bill s Jul 20 '13 at 20:29

We can go for this

a = {{a1, a2}, {b1, b2}};
b = {{x1, x2}, {y1, y2}};
MapThread[{#1, #2} &, Flatten /@ {a, b}]


{{a1, x1}, {a2, x2}, {b1, y1}, {b2, y2}}

If you persist on having a c you can do this

Partition[Transpose[Flatten /@ {a, b}], Length@b]


{{{a1, x1}, {a2, x2}}, {{b1, y1}, {b2, y2}}}

• Thanks for the answer. Actually the first one is fine. I don't need intermediate results. Thanks Plato. :) //Nietzsche. – Friedrich Nietzsche Jul 14 '13 at 21:22

You only need flatten:

Flatten[{A, B}, {{2, 3}, {1}}]


{{a1, x1}, {a2, x2}, {b1, y1}, {b2, y2}}

• Nice to see Flatten[]! – J. M. is away Jul 30 '17 at 14:32

Two more alternatives:

Thread[Flatten /@ {a, b}]
Inner[List, Flatten@a, Flatten@b, List]


{{a1, x1}, {a2, x2}, {b1, y1}, {b2, y2}}