Matlab vs Python: Reshape

Viewed 15894

So I found this:

When converting MATLAB code it might be necessary to first reshape a matrix to a linear sequence, perform some indexing operations and then reshape back. As reshape (usually) produces views onto the same storage, it should be possible to do this fairly efficiently.

Note that the scan order used by reshape in Numpy defaults to the 'C' order, whereas MATLAB uses the Fortran order. If you are simply converting to a linear sequence and back this doesn't matter. But if you are converting reshapes from MATLAB code which relies on the scan order, then this MATLAB code:

z = reshape(x,3,4);

should become

z = x.reshape(3,4,order='F').copy()

in Numpy.

I have a multidimensional 16*2 array called mafs, when I do in MATLAB:

mafs2 = reshape(mafs,[4,4,2]) 

I get something different than when in python I do:

mafs2 = reshape(mafs,(4,4,2))

or even

mafs2 = mafs.reshape((4,4,2),order='F').copy()

Any help on this? Thank you all.

2 Answers

I was having a similar issue myself, as I am also trying to make the transition from MATLAB to Python. I was finally able to convert a numpy matrix, given in depth, row, col, format to a single sheet of column vectors (per image).

In MATLAB I would have done something like:

output = reshape(imStack,[row*col,depth])

In Python this seems to translate to:

import numpy as np
output=np.transpose(imStack)
output=output.reshape((row*col, depth), order='F')
Related