[SciPy-user] array vs matrix, converting code from matlab

Travis Oliphant oliphant at ee.byu.edu
Thu Apr 20 15:44:06 CDT 2006


Gennan Chen wrote:

>Hi! Travis,
>
>Let's start with an example under matlab:
>
> >> d = [0:23]
> >> k = reshape(d, 3,4,2)
>k(:,:,1) =
>0  3  6  9
>1  4  7  10
>2  5  8  11
>k(:,:,2) =
>12  15  18  21
>13  16  19  22
>14  17  20  23
>
>  
>

This is a FORTRAN-order reshaping.   The linear sequence of values is 
reshaped into an array by varying the first index (the row) the fastest.   

NumPy, by default, uses C-contiguous order so that the last index varies 
the fastest as it places elements in the array.

NumPy does have support for the FORTRAN-order, but there are a few 
constructs that don't support it: (arr.flat iterators are always in 
C-contiguous order and a.shape = (3,4,2) always assumes C-contiguous 
order for advancing through the elements).   I don't know of anyone who 
has used the FORTRAN  support to successfully convert MATLAB code  so 
unless you want to be a guinea pig, you might want to just hunker down 
and convert to C-contiguous order.  Alternatively you can just re-think 
the shape of your arrays in reverse:  i.e. instead of creating a 3,4,2 
array,  create a 2,4,3 array and reverse all your indices.

>So, if I want to port my Matlab code, I need to pay attention to  
>this. And Since I  have a lot of C/C++  mexing code in Matlab, I need  
>to fix not just 1-0 based but also indexing issue here. Any chance I  
>can make the indexing like the Matlab's way?  Or I should just hunker  
>down...
>  
>
As far as the indexing is concerned.  The only way to alter it is to 
implement a new class that subtracts 1 from all the indices.  You could 
also define "end" as a simple object and when you see it replace with 
the number of dimension in the array.   Such a thing is possible (you 
could also implement it to reverse the order of all your indices and 
simulate a matlab-style array). 

-Travis




More information about the SciPy-user mailing list