# reshape not like matlab

Hello,

I was surprised to discover recently that the RESHAPE
function in Python and Matlab do not yield the same result. In fact, Python
reshapes along the rows while Matlab does it along the columns.

For example, the Matlab code:

a=(0:19);

reshape(a,5,4)

ans =

`````` 0     5    10    15

1     6    11    16

2     7    12    17

3     8    13    18

4     9    14    19
``````

And the Python equivalent:

a=arange(20)

reshape(a,(5,4))

[[ 0, 1, 2, 3, ]

[ 4, 5, 6, 7, ]

[ 8, 9,10,11, ]

[12,13,14,15,]

[16,17,18,19,]]

To obtain the same result, I should write:

transpose(reshape(a,(4,5)))

Does anyone have an explanation for this? Is it
possible to change the axis priority like e.g., in concatenate?

Thank you,

Dimitri D’Or

Dimitri D'Or wrote:

I was surprised to discover recently that the RESHAPE function in Python and Matlab do not yield the same result. In fact, Python reshapes along the rows while Matlab does it along the columns.

Does anyone have an explanation for this?

AFAIK, the reason is that MATLAB has Fortran in it's history, ans thus uses Fortran semantics laying out arrays, whereas Numeric and numarray use C semantics for laying out arrays.

NumPy is not Matlab, nor is it trying to be.

Is it possible to change the axis priority like e.g., in concatenate?

It doesn't look like it, from the docs. The reason is that re-shape doesn't move any data around in memory, it just changes the way the data is interpreted.

What you want really is a transpose, as you've discovered, but think about whether you really want that... it might make more sense to just stick with NumPy's natural ordering.

This, by the way is a Numeric or numarray question, you'd be best off referring to the docs for those packages, and asking questions on the numpy-discussion list.

-Chris

···

--
Christopher Barker, Ph.D.
Oceanographer

NOAA/OR&R/HAZMAT (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception

Chris.Barker@...259...