2

My question is how to turn a 4-level matrix (notice one extra level)

A = {{{{1, 2, 3}, {4, 5, 6}}}, {{{7, 8, 9}, {10, 11, 12}}}};

into the following:

B = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}};

I think Flatten might do the job but I was unable to understand how it works, especially with these matrix second argument.

So a more general question: is there a way to detect extra levels and eliminate them all together?

I am using Mathematica 10.4.1

Kaa1el
  • 561
  • 4
  • 9

3 Answers3

8

In this case, I would recommend ArrayReshape, which I think is easy to understand

Let

a = {{{{1, 2, 3}, {4, 5, 6}}}, {{{7, 8, 9}, {10, 11, 12}}}};
b = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}};

Now

Dimensions[b]

{2, 2, 3}

So you want a to be reshaped into a 2 x 2 x 3 array; therefore,

ArrayReshape[a, {2, 2, 3}] == b

True

Update

ArrayReshape can easily handle complicated cases of unwanted extra levels of List wrapping, which is something Mathematica is prone to produce. In general one can use

ArrayReshape[list, DeleteCases[Dimensions[list], 1]]

to unwrap sub-lists of one element. Thus,

ArrayReshape[a, DeleteCases[Dimensions[a], 1]] == b

True

and

c = {{{{{{1}, {2}, {3}}, {{4}, {5}, {6}}}}, {{{{7}, {8}, {9}}, {{10}, {11}, {12}}}}}}
ArrayReshape[c, DeleteCases[Dimensions[c], 1]] == b

True

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • You might consider addition a few of these points to Michael's answer here: (105866) – Mr.Wizard Aug 02 '16 at 07:01
  • @Mr.Wizard. I added a comment to the answer you cite that links to this answer. I hope that's sufficient -- I feel uncomfortable making substantive edits to the answers. of others. – m_goldberg Aug 02 '16 at 12:58
4

Example

a = {{{{1, 2, 3}, {4, 5, 6}}}, {{{7, 8, 9}, {10, 11, 12}}}};
b = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}};

Flatten[a, 1]

Output

{{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}}

Test

Flatten[a, 1] == b

True

e.doroskevic
  • 5,959
  • 1
  • 13
  • 32
3

I use Join @@ (@@ is shorthand for Apply) most of the time but version 10 introduced Catenate which is now arguably the canonical method:

Catenate[A] === B   (* True *)

Be aware however that Catenate and Flatten unpack; this just came up in

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371