Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a matrix of matrices, given in the following code. I want to flatten the array...

e1[l_] = Table[{KroneckerDelta[l, m]}, {m, 1, 2}];

σ[l_, m_, k_] = e1[l].Transpose[e1[m]]; 
na = 4;
Sigma[l_, m_] := TensorProduct @@ Table[ σ[l, m, k], {k, 1, na}]
Sigma[1, 1] // MatrixForm

enter image description here

I can do this, but if na is very large then this method:

ArrayFlatten[ArrayFlatten[ArrayFlatten[ArrayFlatten[Sigma[1, 1]]]]] // MatrixForm

is not convenient.

share|improve this question
One way: Nest[ArrayFlatten, Sigma[1, 1], 3] – C. E. Oct 18 '13 at 22:04
up vote 12 down vote accepted

I'd use FixedPoint:

FixedPoint[ ArrayFlatten, Sigma[1, 1]]

We have:

ArrayFlatten[ ArrayFlatten[ ArrayFlatten[ ArrayFlatten[ Sigma[1, 1]]]]] ==
FixedPoint[ ArrayFlatten, Sigma[1, 1]]


FixedPoint[ ArrayFlatten, Sigma[1, 1]] // MatrixForm

enter image description here

share|improve this answer

Another way is


Or in general

Flatten[#, Transpose@Partition[Range@ArrayDepth[#], 2]] &


s = RandomReal[1.0, {2, 2, 2, 2, 2, 2, 2, 2}];

ArrayFlatten@ArrayFlatten@ArrayFlatten@ArrayFlatten[s] == 
    Flatten[#, Transpose@Partition[Range@ArrayDepth[#], 2]] &[s]


share|improve this answer

You can use Fold ignoring the second argument:

Fold[ArrayFlatten[#1] &, Sigma[1, 1], Range @ 4]


ArrayFlatten[ArrayFlatten[ArrayFlatten[ArrayFlatten[Sigma[1, 1]]]]] == 
 Fold[ArrayFlatten[#1] &, Sigma[1, 1], Range[4]]


share|improve this answer

Your Answer


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.