10
$\begingroup$

I am struggling with the task to merge four matrices as presented below. Since the matrices A-D contain more than just four entries it would be too complex to do it by hand. Is there a simple or clever way to get the result in Mathematica?

A = {{A11,A12},
      {A21,A22}}

B = {{B11,B12},
      {B21,B22}}

C = {{C11,C12},
      {C21,C22}}

D = {{D11,D12},
      {D21,D22}}


E = {{A11,B11,A12,B12},
      {C11,D11,C12,D12},
      {A21,B21,A22,B22},
      {C21,D21,C22,D22}}

Thanks in advance. :)

Max

$\endgroup$
2
  • $\begingroup$ Look for Join in the documentation $\endgroup$
    – Fraccalo
    Dec 8, 2019 at 18:44
  • $\begingroup$ I have seen Join in the documentation already, but how can I use it to get the distribution I am looking for? I don't understand this point. $\endgroup$
    – Max
    Dec 8, 2019 at 18:58

3 Answers 3

13
$\begingroup$

Not necessarily optimal, but it works:

a = {{A11, A12}, {A21, A22}};

b = {{B11, B12}, {B21, B22}};

c = {{C11, C12}, {C21, C22}};

d = {{D11, D12}, {D21, D22}};

Flatten[{{a, b}, {c, d}}, {{3, 1}, {4, 2}}]
{{A11, B11, A12, B12},
 {C11, D11, C12, D12},
 {A21, B21, A22, B22},
 {C21, D21, C22, D22}}
$\endgroup$
10
$\begingroup$
a = {{A11, A12}, {A21, A22}};
b = {{B11, B12}, {B21, B22}};
c = {{C11, C12}, {C21, C22}};
d = {{D11, D12}, {D21, D22}};

ArrayFlatten[Transpose[{{a, b}, {c, d}}, {3, 4, 1, 2}]]
(*    {{A11, B11, A12, B12},
       {C11, D11, C12, D12},
       {A21, B21, A22, B22},
       {C21, D21, C22, D22}}    *)
$\endgroup$
8
$\begingroup$

A (probably) very slow but very explicit solution:

a = {{A11, A12}, {A21, A22}};
b = {{B11, B12}, {B21, B22}};
c = {{C11, C12}, {C21, C22}};
d = {{D11, D12}, {D21, D22}};

Riffle[
 MapThread[Riffle, {a, b}],
 MapThread[Riffle, {c, d}]
 ]
{
  {A11, B11, A12, B12}, 
  {C11, D11, C12, D12}, 
  {A21, B21, A22, B22}, 
  {C21, D21, C22, D22}
}
$\endgroup$
1
  • $\begingroup$ Thank you all very much :) $\endgroup$
    – Max
    Dec 8, 2019 at 21:13

Your Answer

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

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