Search code examples
numpymatlabarray-indexing

Indices in Numpy and MATLAB


I have a piece of code in Matlab that I want to convert into Python/numpy.

I have a matrix ind which has the dimensions (32768, 24). I have another matrix X which has the dimensions (98304, 6). When I perform the operation

result = X(ind)

the shape of the matrix is (32768, 24).

but in numpy when I perform the same shape

result = X[ind]

I get the shape of the result matrix as (32768, 24, 6).

I would greatly appreciate it if someone can help me with why I can these two different results and how can I fix them. I would want to get the shape (32768, 24) for the result matrix in numpy as well


Solution

  • In Octave, if I define:

    >> X=diag([1,2,3,4])
    X =
    
    Diagonal Matrix
    
       1   0   0   0
       0   2   0   0
       0   0   3   0
       0   0   0   4
    
    >> idx = [6 7;10 11]      
    idx =
    
        6    7
       10   11
    

    then the indexing selects a block:

    >> X(idx)
    ans =
    
       2   0
       0   3
    

    The numpy equivalent is

    In [312]: X=np.diag([1,2,3,4])
    In [313]: X
    Out[313]: 
    array([[1, 0, 0, 0],
           [0, 2, 0, 0],
           [0, 0, 3, 0],
           [0, 0, 0, 4]])
    In [314]: idx = np.array([[5,6],[9,10]])   # shifted for 0 base indexing
    In [315]: np.unravel_index(idx,(4,4))      # raveled to unraveled conversion
    Out[315]: 
    (array([[1, 1],
            [2, 2]]),
     array([[1, 2],
            [1, 2]]))
    In [316]: X[_]         # this indexes with a tuple of arrays
    Out[316]: 
    array([[2, 0],
           [0, 3]])
    

    another way:

    In [318]: X.flat[idx]
    Out[318]: 
    array([[2, 0],
           [0, 3]])