0

I am trying to port a code from Matlab to Python, which involves slicing a 2D numpy array with another boolean array.

z = np.array([[1,2,3],[4,5,6],[7,8,9]])
f = np.array([True,True,False])
print(z[f,f])

Result is a 1D array [1,5]

In Matlab this would return the upper left 2x2 part of z, which is [[1,2],[4,5]].

How can I achieve a similar effect?

  • In MATLAB how would you fetch this portion of the diagonal? – hpaulj Jul 30 '19 at 14:46
  • @hpaulj you need to either create a 3x3 boolean matrix or use diag to get the diagonal first. the suggested solution(np.ix_) in the existing post is very slow according to my profiler. I need a faster alternative. – Cowboy Trader Jul 30 '19 at 16:05
  • I was thinking of `sub2ind` which translates indexing tuples into linear indices. In `numpy` indexing block with slices is fast, `a[0:2, 0:2]`, but the `ix_` approach effectively creates a Cartesian product of indexes, i.e. n*n elements that have to be copied. For large arrays such a copy will be noticeably slower than a `view`. – hpaulj Jul 30 '19 at 17:45
  • @hpaulj The alternative solution in the link seems to be better x[row_indices,:][:,col_indices] – Cowboy Trader Jul 30 '19 at 17:56

0 Answers0