# Flatten a four dimensional array into a matrix

What is the simplest way to transform an array of the form

{{{{a11, a12}, {a21, a22}},
{{a13, a14}, {a23, a24}}},
{{{a31, a32}, {a41, a42}},
{{a33, a34}, {a43, a44}}}}


To the matrix

{{a11,a12,a13,a14},
{a21,a22,a23,a24},
{a31,a32,a33,a34},
{a41,a42,a43,a44}}


I understand I should use Flatten, but I cannot figure out how to denote the levels.

ArrayFlatten is the ticket:

a = {{{{a11, a12}, {a21, a22}}, {{a13, a14}, {a23, a24}}}, {{{a31, a32}, {a41, a42}}, {{a33, a34}, {a43, a44}}}};
b = {{a11, a12, a13, a14}, {a21, a22, a23, a24}, {a31, a32, a33, a34}, {a41, a42, a43, a44}};

ArrayFlatten[a] == b
(* True *)


As Roman says, ArrayFlatten is the simplest, but you could use Flatten as well:

Flatten[
{
{{{a11,a12},{a21,a22}},{{a13,a14},{a23,a24}}},
{{{a31,a32},{a41,a42}},{{a33,a34},{a43,a44}}}
},
{{1,3}, {2,4}}
] //TeXForm


$$\left( \begin{array}{cccc} \text{a11} & \text{a12} & \text{a13} & \text{a14} \\ \text{a21} & \text{a22} & \text{a23} & \text{a24} \\ \text{a31} & \text{a32} & \text{a33} & \text{a34} \\ \text{a41} & \text{a42} & \text{a43} & \text{a44} \\ \end{array} \right)$$

• Is there any simple explanation why {{1,3},{2,4}} works? – tst May 9 '19 at 21:19
• @tst: If you don't feel like dealing with the Flatten[] levels, you can also Flatten it "all the way" and then Partition it back into 4-element lists, e.g.,  {{{{a11, a12}, {a21, a22}}, {{a13, a14}, {a23, a24}}}, {{{a31, a32}, {a41, a42}}, {{a33, a34}, {a43, a44}}}} // Flatten // Partition[#, 4]&  – Joshua Schrier May 9 '19 at 21:24
• @tst Explanations about {{1,3},{2,4}} can be found in Flatten command: matrix as second argument. Not sure about "simple", however :) – WReach May 9 '19 at 21:41