Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
    
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

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer
    
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}}}

share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.