3

Using the numpy function numpy.nonzero, is there an elegant way to check if the tuples as output are empty arrays?

In MATLAB, this is very easy

i.e.

answer = find( matrix_a < matrix_b );
isempty(answer)
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
overcomer
  • 2,244
  • 3
  • 26
  • 39

2 Answers2

6

The numpythonic way of doing this is to use any/all methods on the ndarray objects directly.

In your example case, your code is asking: Are there no indices where matrix_a is less than matrix_b?

not (matrix_a < matrix_b).any()

Equivalently, does matrix_a have all elements greater than the corresponding elements in matrix_b?

(matrix_a >= matrix_b).all()
wim
  • 338,267
  • 99
  • 616
  • 750
  • I think you are confused - `__builtin__.any(np.array([0]))` is false and so is `np.any(np.array([0]))`. It should be true. To see the weird edge case consider for example with `a = zeros((3,4)); b = zeros((3,4)); b[0,0] = 1` – wim May 05 '15 at 03:33
  • Sorry, I did confuse myself there. I expected `np.any` to be false, which I thought was what you wanted, and `__builtin__.any` to be true, which I thought was wrong. But both are false anyway. – abarnert May 05 '15 at 03:35
4

For a (10,10) range(100)

In [201]: np.nonzero(a>100)
Out[201]: (array([], dtype=int32), array([], dtype=int32))

nonzero returns a tuple, with an array for each dimension. This tuple can be used to index all the elements where the condition is true.

So you could test for 'empty' nonzero by looking at the length of one of those arrays.

len(np.nonzero(a>98)[0])==0

any on the boolean mask appears simpler, though in quick tests, it is actually slower.

np.any(a>98)

The MATLAB 'find' returns the items that match. The numpy equivalent is a[np.nonzero(a>100)], or using the boolean mask directly a[a>100].

So my new nomination for a fast isempty(find...)) look alike is len(a[...])==0.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Checking the length of the first array of the tuple was my solution but it didn't seem to me elegant. That's why my question. Thanks for testing the efficiency too. – overcomer May 05 '15 at 07:32
  • In MATLAB is `isempty(find())` more elegant than `any()`? – hpaulj May 05 '15 at 16:25
  • Of course `any()` is very elegant, I meant `len(np.nonzero(a>98)[0])`, ...checking the length of the first array of the tuple, that was the solution that I found. I am glad that is more efficient, because I have a lot of problem of slowness in my application. So I will keep it. – overcomer May 05 '15 at 16:33