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

Gennan Chen gnchen at cortechs.net
Thu Apr 20 14:46:26 EDT 2006


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


under numpy:

 >In [2]: d = numpy.asarray(range(0,24), numpy.float32)

In [3]: d
Out[3]:
array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
         11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,   
21.,
         22.,  23.], dtype=float32)

In [4]: k = d.reshape(3,4,2)

In [5]: k
Out[5]:
array([[[  0.,   1.],
         [  2.,   3.],
         [  4.,   5.],
         [  6.,   7.]],

        [[  8.,   9.],
         [ 10.,  11.],
         [ 12.,  13.],
         [ 14.,  15.]],

        [[ 16.,  17.],
         [ 18.,  19.],
         [ 20.,  21.],
         [ 22.,  23.]]], dtype=float32)

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...

Gen-Nan Chen, PhD
Chief Scientist
Research and Development Group
CorTechs Labs Inc (www.cortechs.net)
1020 Prospect St., #304, La Jolla, CA, 92037
Tel: 1-858-459-9700 ext 16
Fax: 1-858-459-9705
Email: gnchen at cortechs.net


On Apr 20, 2006, at 11:28 AM, Travis Oliphant wrote:

> Gennan Chen wrote:
>
>> Hi! All,
>>
>> I am also in the same process. And I would like to add one more
>> question:
>>
>> In Matlab, for a 3D array or matrix, the indexing is a(i,j,k). In
>> numpy, it became a[k-1,i-1,j-1]. Is there any way to make it become
>> a[i-1,j-1,k-1]? Or I am doing something wrong here??
>>
>>
>>
>
> In NumPy, arrays and matrices are by default in  C-contiguous order so
> that the last index varies the fastest.    Matlab is based on Fortran
> originally and defines arrays in Fortran-contiguous order (the first
> index varies the fastest as you walk linearly throught memory).      
> The
> only time this really matters is if you are interfacing with some
> compiled code.   Otherwise, how you think about indexing is up to you
> and how you define the array.
>
> So,  to make it a[i-1,j-1,k-1] you need to reshape the array from the
> way you defined it in MATLAB.    It really does just depend on how you
> define things.  Perhaps you could give a specific example  so we could
> be more specific on how you would write the same thing in NumPy.
>
> -Travis
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.net
> http://www.scipy.net/mailman/listinfo/scipy-user
>




More information about the SciPy-User mailing list