7
$\begingroup$

I am trying to flatten a matrix from 3-dimensional to 2-dimensional one.

The original one has dimension for example {10,120,120}:

list1 = RandomReal[1, {10, 120, 120}];

I want to convert it to a new matrix with {10,120*120} dimension. I am using:

On["Packing"]  (*For checking if exist unpacked arrays *)  
Flatten[Map[Flatten, {list1}, {-3}], 1];

But this will generate unpacked array. How should I avoid this issue?

$\endgroup$
2
  • 4
    $\begingroup$ Try Flatten[list1, {{1}, {2, 3}}]. $\endgroup$ Commented Mar 5, 2019 at 2:18
  • $\begingroup$ Thanks, it works! $\endgroup$
    – cj9435042
    Commented Mar 5, 2019 at 2:26

1 Answer 1

15
$\begingroup$

An alternative to using Flatten as in the comments is to use ArrayReshape. For large arrays, ArrayReshape should be significantly faster. For example:

list1 = RandomReal[1, {10, 1200, 1200}];

Comparison:

r1 = Flatten[list1, {{1}, {2, 3}}]; //RepeatedTiming
r2 = ArrayReshape[list1, {10, 1200 1200}]; //RepeatedTiming

r1 === r2

{0.120, Null}

{0.025, Null}

True

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.