How to reshape matrices in Mathematica

0 votes
asked Mar 18, 2010 by speciousfool

When manipulating matrices it is often convenient to change their shape. For instance, to turn an N x M sized matrix into a vector of length N X M. In MATLAB a reshape function exists:

RESHAPE(X,M,N) returns the M-by-N matrix whose elements are taken columnwise from X. An error results if X does not have M*N elements.

In the case of converting between a matrix and vector I can use the Mathematica function Flatten which takes advantage of Mathematica's nested list representation for matrices. As a quick example, suppose I have a matrix X:

4x4 matrix

With Flatten[X] I can get the vector {1,2,3,...,16}. But what would be far more useful is something akin to applying Matlab's reshape(X,2,8) which would result in the following Matrix:

4x4 matrix

This would allow creation of arbitrary matrices as long as the dimensions equal N*M. As far as I can tell, there isn't anything built in which makes me wonder if someone hasn't coded up a Reshape function of their own.

5 Answers

0 votes
answered Mar 18, 2010 by kennytm
Reshape[mtx_, _, n_] := Partition[Flatten[mtx], n]
0 votes
answered Jan 5, 2012 by quantum-oli

I know this is an old thread but for the sake of the archives and google searches I've got a more general way that allows a length m*n*... list to be turned into an m*n*... array:

Reshape[list_, shape__] := Module[{i = 1},
  NestWhile[Partition[#, shape[[i]]] &, list, ++i <= Length[shape] &]
  ]

Eg:

In:= Reshape[Range[8], {2, 2, 2}]

Out:= {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
0 votes
answered Mar 4, 2012 by bob-jones
Reshape[list_, dimensions_] := 
First[Fold[Partition[#1, #2] &, Flatten[list], Reverse[dimensions]]]

Example Usage:

In: Reshape[{1,2,3,4,5,6},{2,3}]

Out: {{1,2,3},{4,5,6}}

This works with arrays of arbitrary depth.

0 votes
answered Mar 9, 2013 by matthias-odisio

ArrayReshape does exactly that.

0 votes
answered Sep 15, 2017 by putnik11

There is now also a new function ArrayReshape[].

Example:

{{1, 2, 3}, {4, 5, 6}} // MatrixForm

ArrayReshape[{{1, 2, 3}, {4, 5, 6}}, {3, 2}] // MatrixForm
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...