Consider the tensor (t1) in the next cell.
Clear[t1] ; t1 = {{{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}},
{{2, 2, 2}, {2, 2, 2}, {2, 2, 2}}},
{{{3, 3, 3}, {3, 3, 3}, {3, 3, 3}},
{{4, 4, 4}, {4, 4, 4}, {4, 4, 4}}}} ; MatrixForm[t1]
( ( 1 1 1 ) ( 2 2 2 ) )
1 1 1 2 2 2
1 1 1 2 2 2
( 3 3 3 ) ( 4 4 4 )
3 3 3 4 4 4
3 3 3 4 4 4
A user in the MathGroup wanted to express this tensor as a matrix with MatrixForm in the next cell. Visually this is simple. However, the complicated structure of a tensor makes it a challenge to write an elegant program that makes the conversion.
( 1 1 1 2 2 2 )
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4
Allan Hayes provided the following two solutions in the MathGroup.
t2 = Apply[Join, Join @@ Transpose[t1, {1, 3, 2}], 1 ] ; MatrixForm[t2]
( 1 1 1 2 2 2 )
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4
t2 = Flatten[Map[Flatten, Transpose[t1, {1, 3, 2}], {2}], 1] ;
MatrixForm[t2]
( 1 1 1 2 2 2 )
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4
Now suppose you want to do the same thing on the higher rank tensor (t1) below
m1 = { { {{11, 11}, {11, 11}}, {{12, 12}, {12, 12}}},
{ {{13, 13}, {13, 13}}, {{14, 14}, {14, 14}} }} ; m2 = { { {{15, 15}, {15, 15}}, {{16, 16}, {16, 16}}},
{ {{17, 17}, {17, 17}}, {{18, 18}, {18, 18}} }} ; m3 = { { {{19, 19}, {19, 19}}, {{20, 20}, {20, 20}}},
{ {{21, 21}, {21, 21}}, {{22, 22}, {22, 22}} }} ; m4 = { { {{23, 23}, {23, 23}}, {{24, 24}, {24, 24}}},
{ {{25, 25}, {25, 25}}, {{26, 26}, {26, 26}} }} ; t1 = {{m1, m2}, {m3, m4}} ; MatrixForm[t1]
( ( 11 11 ) ( 12 12 ) )
( 11 11 12 12 )
( 13 13 ) ( 14 14 )
13 13 14 14
( ( 15 15 ) ( 16 16 ) )
15 15 16 16
( 17 17 ) ( 18 18 )
17 17 18 18
( ( 19 19 ) ( 20 20 ) )
19 19 20 20
( 21 21 ) ( 22 22 )
21 21 22 22
( ( 23 23 ) ( 24 24 ) )
23 23 24 24
( 25 25 ) ( 26 26 )
25 25 26 26
Mathematica Version 4 has a NestWhile function that comes in handy here. The code in the next cell will merge together tensors of any rank.
t2 = NestWhile[Apply[Join, Join @@ Transpose[#, {1, 3, 2}], 1 ] &
, t1 , TensorRank[#] > 2 & ] ; MatrixForm[t2]
( 11 11 12 12 15 15 16 16 )
11 11 12 12 15 15 16 16
13 13 14 14 17 17 18 18
13 13 14 14 17 17 18 18
19 19 20 20 23 23 24 24
19 19 20 20 23 23 24 24
21 21 22 22 25 25 26 26
21 21 22 22 25 25 26 26