0

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

Wolfie
  • 27,562
  • 7
  • 28
  • 55
  • 1
    In the numpy case `ind` applies only to the first dimension, e.g. `X[ind,:]` – hpaulj Jul 23 '21 at 14:31
  • @hpaulj this doesn't have any effect in this case. Even if I do what you have suggested, I still get the same results. – Daniel Sempere Jul 23 '21 at 14:38
  • I didn't suggest anything! – hpaulj Jul 23 '21 at 14:45
  • What exactly is the MATLAB doing? What are the values of `ind` (relative to the shape of `X`)? My MATLAB coding well in the past, so I can't quite picture the action. I could fire up `Octave` and do some experimenting, but I prefer that you explain it. – hpaulj Jul 23 '21 at 19:34

1 Answers1

0

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]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353