# What is the best way to flatten a nested list?

I have a list called matcoeffE which has dimensions {10, 9, 7, 2}. However, I want to build a matrix with dimensions {180,7} and then export it as an Excel file. At the first step I used:

newmat = FlattenAt[matcoeffE, Transpose[{Range[10]}]];


so dimensions of newmat became {90, 7, 2}. After that I have to flatten 2 (2*90) and get a new matrix which has dimensions {180,7} which produces an Excel file with 190 rows and 7 columns (in a single sheet). My mean is: newmat has 90 rows and 7 columns which each column has two numbers in it. I want to second number of each this two-member list goes to the next row (namely each second member is placed under the first member), so that the dimensions will be {180,7}. I tried to show my mean schematically as follows:

I tried Splice for example, but it didn't work. In fact I always have a problem with flattening the nested list. How can I solve my problem? Is there a simple and general way to flatten nested lists?

• To do the first part, you could use newmat = ArrayReshape[matcoeffE, {90, 7, 2}]; but I do not understand the rest of your question now. Oct 24 at 9:10
• @Nasser See my updates Oct 24 at 9:25
• What do you mean by "my mean"? Oct 24 at 19:17

Code is the best illustration

a = RandomReal[{0, 1}, {10, 9, 7, 2}];
Dimensions[a]
(*{10, 9, 7, 2}*)

b = Transpose[a, {1, 2, 4, 3}];
Dimensions[b]
(*{10, 9, 2, 7}*)

c1 = Flatten[b, 1];
Dimensions[c1]
(*{90, 2, 7}*)

c2 = Flatten[b, 2];
Dimensions[c2]
(*{180, 7}*)


One can do everything at once

c3 = Flatten[a, {{1, 2, 4}, {3}}];
Dimensions[c3]
(*{180, 7}*)


And verify

Norm[c3 - c2]
(* 0 *)


## Explanations

There are some differences between Transpose and Flatten that one needs to take care of.

• If you write b = Transpose[a, {1, 2, 4, 3}] it means that the 3rd dimension of a will become the 4th dimension of b. That is, {1, 2, 4, 3} denotes the destination of dimensions.
• Let the second argument of Flatten be n. n+1 tells you how many dimensions starting from the first one will be combined together. This means Flatten[b, 2] combines 3 first dimensions into one.
• Flatten with a 2nd argument being a list is slightly different: Flatten[a, {{1, 2, 4}, {3}}] means combine dimensions 1, 2 and 4 into the first dimension, combine dimension 3 into the second dimension. And so on. As you can see this is very flexible as it allows to transpose and flatten at the same time.
• Thank you soooooo much, can you add some explanations to your answer? I really need to understand the way Flatten works, for example how you build c3 in one step? Oct 24 at 10:11
• @Wisdom Yes, see the edits Oct 24 at 10:29
• Good job and great trick! However I need to practice it to understand deeply. Thanks again. Oct 24 at 10:33
• @Wisdom see also Flatten command: matrix as second argument Oct 24 at 18:54