Getting Matrix Grid Using Logical Indexing in Numpy

I am trying to rewrite a function using numpy, which was originally in MATLAB. MATLAB has the logical part of indexing:

X = reshape(1:16, 4, 4).'; idx = [true, false, false, true]; X(idx, idx) ans = 1 4 13 16 

When I try to do this in numpy, I cannot get the correct indexing:

 X = np.arange(1, 17).reshape(4, 4) idx = [True, False, False, True] X[idx, idx] # Output: array([6, 1, 1, 6]) 

What is the correct way to get a grid from a matrix through logical indexing?

+6
source share
3 answers

You can also write:

 >>> X[np.ix_(idx,idx)] array([[ 1, 4], [13, 16]]) 
+7
source
 In [1]: X = np.arange(1, 17).reshape(4, 4) In [2]: idx = np.array([True, False, False, True]) # note that here idx has to # be an array (not a list) # or boolean values will be # interpreted as integers In [3]: X[idx][:,idx] Out[3]: array([[ 1, 4], [13, 16]]) 
+4
source

In numpy this is called fancy indexing . To get the elements you need, you must use an array of 2D indexes.

You can use outer to make a valid 2D index array from your 1D idx . Outers applied to two 1D sequences compare each element of one sequence with each element of the other. Recalling that True*True=True and False*True=False , np.multiply.outer() , which is the same as np.outer() , can give you 2D indices:

 idx_2D = np.outer(idx,idx) #array([[ True, False, False, True], # [False, False, False, False], # [False, False, False, False], # [ True, False, False, True]], dtype=bool) 

What you can use:

 x[ idx_2D ] array([ 1, 4, 13, 16]) 

In your real code, you can use x=[np.outer(idx,idx)] , but it does not save memory, working just as if you turned on del idx_2D after the slice was executed.

+2
source

Source: https://habr.com/ru/post/948192/


All Articles