Numpy array and Matlab Matrix are mismatching [3D]

前端 未结 5 1494
失恋的感觉
失恋的感觉 2021-01-06 17:32

The following octave code shows a sample 3D matrix using Octave/Matlab

octave:1> A=zeros(3,3,3);
octave:2> 
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7         


        
5条回答
  •  生来不讨喜
    2021-01-06 17:55

    MATLAB and Python index differently. To investigate this, lets create a linear array of number 1 to 8 and then reshape the result to be a 2-by-2-by-2 matrix in each language:

    MATLAB:

    M_flat = 1:8
    M = reshape(M_flat, [2,2,2])
    

    which returns

    M =
    
    ans(:,:,1) =
    
       1   3
       2   4
    
    ans(:,:,2) =
    
       5   7
       6   8
    

    Python:

    import numpy as np
    P_flat = np.array(range(1,9))
    P = np.reshape(P, [2,2,2])
    

    which returns

    array([[[1, 2],
            [3, 4]],
    
           [[5, 6],
            [7, 8]]])
    

    The first thing you should notice is that the first two dimensions have switched. This is because MATLAB uses column-major indexing which means we count down the columns first whereas Python use row-major indexing and hence it counts across the rows first.

    Now let's try indexing them. So let's try slicing along the different dimensions. In MATLAB, I know to get a slice out of the third dimension I can do

    M(:,:,1)
    
    ans =
    
       1   3
       2   4
    

    Now let's try the same in Python

    P[:,:,0]
    
    array([[1, 3],
           [5, 7]])
    

    So that's completely different. To get the MATLAB 'equivalent' we need to go

    P[0,:,:]
    
    array([[1, 2],
           [3, 4]])
    

    Now this returns the transpose of the MATLAB version which is to be expected due the the row-major vs column-major difference.

    So what does this mean for indexing? It looks like Python puts the major index at the end which is the reverse of MALTAB.

    Let's say I index as follows in MATLAB

    M(1,2,2)
    
    ans = 
    
        7
    

    now to get the 7 from Python we should go

    P(1,1,0)
    

    which is the MATLAB syntax reversed. Note that is is reversed because we created the Python matrix with a row-major ordering in mind. If you create it as you did in your code you would have to swap the last 2 indices so rather create the matrix correctly in the first place as Ander has suggested in the comments.

提交回复
热议问题