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.
$\begingroup$
$\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$– Friedrich NietzscheCommented Jul 20, 2013 at 20:12
Add a comment
|
4 Answers
$\begingroup$
$\endgroup$
5
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.
-
$\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 andb
is a vector, what do you want the answer to be? $\endgroup$– bill sCommented 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 sCommented Jul 20, 2013 at 20:29
$\begingroup$
$\endgroup$
1
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}}}
-
$\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
$\begingroup$
$\endgroup$
1
You only need flatten:
Flatten[{A, B}, {{2, 3}, {1}}]
{{a1, x1}, {a2, x2}, {b1, y1}, {b2, y2}}
-
$\begingroup$ Nice to see
Flatten[]
! $\endgroup$ Commented Jul 30, 2017 at 14:32
$\begingroup$
$\endgroup$
Two more alternatives:
Thread[Flatten /@ {a, b}]
Inner[List, Flatten@a, Flatten@b, List]
{{a1, x1}, {a2, x2}, {b1, y1}, {b2, y2}}