Search code examples
pythonmatlabnumpymatrix-indexing

Getting a grid of a matrix via logical indexing in Numpy


I'm trying to rewrite a function using numpy which is originally in MATLAB. There's a logical indexing part which is as follows in MATLAB:

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

ans =

     1     4
    13    16

When I try to make it in numpy, I can't 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's the proper way of getting a grid from the matrix via logical indexing?


Solution

  • You could also write:

    >>> X[np.ix_(idx,idx)]
    array([[ 1,  4],
           [13, 16]])