Get data sequentially from numpy array in Matlab ordering

后端 未结 2 441
忘了有多久
忘了有多久 2021-01-20 02:46

As an example, suppose, in Matlab, a Matrix a(2,3,2) like this:

a(:,:,1) =

     1     2     3
     4     5     6


a(:,:,2) =

     7     8             


        
2条回答
  •  感动是毒
    2021-01-20 03:44

    This bugs a lot of people going into NumPy/Python from MATLAB. So, in MATLAB, the indexing format is (column x row x dim3) and so on. With NumPy, it's (axis-0, axis-1, axis-2) and so on.

    To show this schematically using a sample case on MATLAB :

    >> a = reshape(1:27,[3,3,3]);
    >> a
    a(:,:,1) =
    
            row
        --------------->
         1     4     7   |         |
         2     5     8   | col     |
         3     6     9   v         |
    a(:,:,2) =                     |
        10    13    16             | dim3
        11    14    17             |
        12    15    18             |
    a(:,:,3) =                     |
        19    22    25             |
        20    23    26             |
        21    24    27             v
    

    On NumPy :

    In [62]: a = np.arange(27).reshape(3,3,3)
    
    In [63]: a
    Out[63]: 
    
                axis=2
             ---------->
    array([[[ 0,  1,  2],   |          |
            [ 3,  4,  5],   | axis=1   |
            [ 6,  7,  8]],  v          |
                                       |
           [[ 9, 10, 11],              |
            [12, 13, 14],              | axis=0
            [15, 16, 17]],             |
                                       |
           [[18, 19, 20],              |
            [21, 22, 23],              |
            [24, 25, 26]]])            v
    

    Let's try to correlate these dimensions and axes terminology for the 3D array case listed in the question between these two environments :

    MATLAB      NumPy
    ------------------
    cols        axis-1
    rows        axis-2
    dim3        axis-0
    

    Thus, to simulate the same behavior in NumPy as MATLAB, we need the axes in NumPy as : (1,2,0). Together with NumPy's way of storing elements starting from the last axis to the first one i.e. in reversed order, the required axes order would be (0,2,1).

    To perform the permuting of axes that way, we could use np.transpose and thereafter use a flattening operation with np.ravel() -

    a.transpose(0,2,1).ravel()
    

    Sample run -

    In [515]: a
    Out[515]: 
    array([[[ 1,  2,  3],
            [ 4,  5,  6]],
    
           [[ 7,  8,  9],
            [10, 11, 12]]])
    
    In [516]: a.transpose(0,2,1) # Permute axes
    Out[516]: 
    array([[[ 1,  4],
            [ 2,  5],
            [ 3,  6]],
    
           [[ 7, 10],
            [ 8, 11],
            [ 9, 12]]])
    
    In [517]: a.transpose(0,2,1).ravel() # Flattened array
    Out[517]: array([ 1,  4,  2,  5,  3,  6,  7, 10,  8, 11,  9, 12])
    

提交回复
热议问题