TransWikia.com

Array reshaping without explicitly specifying one dimension

Mathematica Asked on June 26, 2021

In NumPy a function numpy.reshape can leave at most one dimensional specification unspecified and it will be automatically calculated.

So is there a similar functionality in MMA? As a simplest example I can think of, when I would like to evenly split a List with an even-number length, can I not explicitly calculate the length of the two sublists?

list = Range[6];
ArrayReshape[#, {2, Length[#]/2}] & [list] (*working*)
Partition[#, Length[#]/2] & [list] (*working*)
ArrayReshape[list, {2, _}] (*not working*)

The last line is my naïve attempt and apparently it does not work.

2 Answers

ArrayReshape doesn't let you do this, but ReshapeLayer does:

ReshapeLayer[{2, Automatic}] @ Range[6]
ReshapeLayer[{Automatic, 2}] @ Range[6]

{{1., 2., 3.}, {4., 5., 6.}}

{{1., 2.}, {3., 4.}, {5., 6.}}

Unfortunately, ReshapeLayer is a neural network function that only works on machine numbers.

Answered by Sjoerd Smit on June 26, 2021

It's easy enough to compute the missing dimension, which the OP shows, although it would be nice if Automatic worked in the way below.

list = Range[24];
dims = {2, Automatic, 4};
ArrayReshape[
 list,
 dims /. Automatic ->  (* drops elements that don't fit new dims which *)
   Quotient[Times @@ Dimensions[list],  (* is what ArrayReshape[] does *)
    Times @@ DeleteCases[dims, Automatic]]]
(*
  {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}},
   {{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}}
*)

General function:

ClearAll[arrayReshape];
arrayReshape[
  a_?ArrayQ, 
  dims : {(_Integer | Automatic) ..} /; Count[dims, Automatic] <= 1, 
  p_ : None] := 
 ArrayReshape[
  a, 
  dims /. Automatic -> 
    Quotient[Times @@ Dimensions[a], 
     Times @@ DeleteCases[dims, Automatic]],
  p]

Example:

ReshapeLayer[{Automatic, 20}]@Range[600] //  Dimensions // RepeatedTiming
arrayReshape[Range[600], {Automatic, 20}] // Dimensions // RepeatedTiming
(*
  {0.0059, {30, 20}}
  {0.0000119, {30, 20}}
*)

One ought to beware that ReshapeLayer has considerable overhead and limitations compared to ArrayReshape.

Answered by Michael E2 on June 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP