Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
2  
One way: Nest[ArrayFlatten, Sigma[1, 1], 3] –  Pickett Oct 18 '13 at 22:04

3 Answers 3

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]]
True

and

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

enter image description here

share|improve this answer

Another way is

Flatten[#,{{1,3,5,7},{2,4,6,8}}]&

Or in general

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

Verification:

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

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

True

share|improve this answer

You can use Fold ignoring the second argument:

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

Check:

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

True

share|improve this answer

Your Answer

 
discard

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.