Search code examples
pythonnumpy

Is there an inverted version of numpy.all()?


As stated in the docs for numpy.all():

numpy.all() tests whether all array elements along a given axis evaluate to True.

Is there a function, that does the opposite: Check whether all array elements along a given axis (I need the diagonal) evaluates to False.

What I need in particular is to check if the diagonal of a 2-dimensional matrix is zero every where.


Solution

  • First, to extract the diagonal, you can use mymatrix.diagonal().

    There are quite a few ways to do what you want.

    To test whether it is zero everywhere you can do numpy.all(mymatrix.diagonal() == 0).

    Alternatively, "everything is equal to zero (False)" is the same as "nothing equal to True", so you could also use not numpy.any(mymatrix.diagonal()).

    Since it's a numeric matrix though, you can just add up the absolute value of the elements on the diagonal and if they're all 0, each element must be zero: numpy.sum(numpy.abs(mymatrix.diagonal()))==0.