Home > Back-end >  Efficient ways to check whether a matrix is zero-matrix in Julia
Efficient ways to check whether a matrix is zero-matrix in Julia

Time:05-17

I have an n-by-n matrix (n-very large) that I want to check whether it is a zero matrix or not in Julia. One of the ways that I tried is the following

using BenchmarkTools
using Random

A = rand(2000,2000); # n = 2000 for instance.
@btime all($A .== 0) 

which outputs to

2.380 ms (4 allocations: 492.59 KiB)
false

Is there any other efficient ways to achieve the same?

CodePudding user response:

There is a dedicated function for finding out whether an object is an 'additive identity', i.e. zero. And this function works also for arrays:

iszero(A)

Internally, this is implemented as all(iszero, A), but I prefer just iszero(A) since it is more generic.

In some cases, such as for sparse arrays, iszero(A) can be much faster than all(iszero, A), since the latter will iterate over every element, while iszero(A) only iterates over the structurally non-zero elements.

CodePudding user response:

Broadcasting == first allocates a new boolean array, which you don't really need. For cases like this, all has a method accepting a predicate as the first argument:

julia> @btime all($A .== 0)
  3.744 ms (4 allocations: 492.59 KiB)
false

julia> @btime all(iszero, $A)
  2.880 ns (0 allocations: 0 bytes)
false

This has the additional advantage of short-circuiting, i.e., stopping after the first false.

  • Related