Search code examples
pythonmatlabnumpycode-translation

Elegant way to check empty result of numpy.nonzero


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)

Solution

  • 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()