Logical indexing in Numpy with two indexes, as in MATLAB

How do I repeat this indexing done in MATLAB using Numpy?

X=magic(5); M=[0,0,1,2,1]; X(M==0,M==2) 

which returns:

 ans = 8 14 

I found that doing this in Numpy is wrong, as it does not give me the same results.

 X = np.matrix([[17, 24, 1, 8, 15], [23, 5, 7, 14, 16], [ 4, 6, 13, 20, 22], [10, 12, 19, 21, 3], [11, 18, 25, 2, 9]]) M=array([0,0,1,2,1]) X.take([M==0]).take([M==2], axis=1) 

since I get:

  matrix([[24, 24, 24, 24, 24]]) 

What is the correct way to boolean indexing with two indexes in numpy?

+2
source share
1 answer

In the general case, there are two ways to interpret X[a, b] , when both a and b are arrays (vectors in matlab), indexing the "internal style" or indexing the "external style".

Matlab designers opted for "external style" indexing, and numpy designers opted for indexing internal style. To index the "external style" in numpy, you can use:

 X[np.ix_(a, b)] # This is roughly equal to matlab's X(a, b) 

for completeness, you can do the indexing of the "internal style" in Matlab by doing:

 X(sub2ind(size(X), a, b)) # This is roughly equal to numpy's X[a, b] 

In short, try X[np.ix_(M == 0, M == 1)] .

+7
source

All Articles