3
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ I have a problem when B is a vector not a matrix, both procedures below do not work. Is there a way around it? $\endgroup$ Commented Jul 20, 2013 at 20:12

4 Answers 4

4
$\begingroup$

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.

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

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}}}

$\endgroup$
1
  • $\begingroup$ Thanks for the answer. Actually the first one is fine. I don't need intermediate results. Thanks Plato. :) //Nietzsche. $\endgroup$ Commented Jul 14, 2013 at 21:22
2
$\begingroup$

You only need flatten:

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

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

$\endgroup$
1
0
$\begingroup$

Two more alternatives:

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

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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