5

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:

Enter image description here

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?

Peter Mortensen
  • 759
  • 4
  • 7
Wisdom
  • 1,258
  • 7
  • 13

1 Answers1

15

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.
yarchik
  • 18,202
  • 2
  • 28
  • 66