What is the fastest way to check if an entire array is zero? For my case the elements of the array are either 1 or 0 but for reference purposes the general case can also be considered.

  • $\begingroup$ You could use Total? $\endgroup$
    – Q.P.
    Oct 13 '20 at 13:31
  • 2
    $\begingroup$ Maybe LinearAlgebra`Private`ZeroArrayQ? I recall that we had a similar question not long ago... $\endgroup$ Oct 13 '20 at 13:40
  • 1
    $\begingroup$ Ah, here it is. Not a duplicate but related and thus maybe of interest: mathematica.stackexchange.com/q/230971 $\endgroup$ Oct 13 '20 at 13:46
  • 1
    $\begingroup$ @Q.P. - Total@matrix returns a vector rather than a scalar. Even if you Flatten the matrix first, you would also need to use Abs to ensure that a zero result indicated that the matrix was all zeroes. $\endgroup$
    – Bob Hanlon
    Oct 13 '20 at 13:52
  • $\begingroup$ @Q.P. Total would work but I'm interested in speed. It might be the fastest but I don't know. $\endgroup$ Oct 13 '20 at 18:53

LinearAlgebra`Private`ZeroArrayQ seems to do quite a good job. Curiously enough, Statistics`Library`ConstantVectorQ[#] && #[[1]] == 0 & tends to be a little bit faster on my machine.


I tested the methods from Henrik and got the following timings

linAlgZeroArrayQ = LinearAlgebra`Private`ZeroArrayQ;
statZeroArrayQ = 
  Statistics`Library`ConstantVectorQ[#] && #[[1]] == 0 &;
totalZeroArrayQ = Total[#] == 0 &;

n = 10^5;
exactZeros = ConstantArray[0, n];
numericalZeros = ConstantArray[0., n];
exactSparse = exactZeros; exactSparse[[n/2]] = 1;
numericalSparse = numericalZeros; numericalSparse[[n/2]] = 1.;
exactRandom = RandomChoice[{0, 1}, n];
numericalRandom = RandomChoice[{0., 1.}, n];

functions = {linAlgZeroArrayQ, statZeroArrayQ, totalZeroArrayQ};
tests = {exactZeros, numericalZeros, exactSparse, numericalSparse, 
   exactRandom, numericalRandom};
results = Table[
   AbsoluteTiming[Do[functions[[j]]@tests[[i]], {10000}]][[1]], {i, 1,
     Length@tests}, {j, 1, Length@functions}

 TableHeadings -> {{"Exact zeros", "Numerical zeros", "Exact sparse", 
    "Numerical sparse", "Exact random", 
    "Numerical random"}, {"Linear Algebra method", 
    "Statistics method", "Total"}}]

enter image description here

For the cases I tested the LinearAlgebra`Private`ZeroArrayQ seems like a clear winner but there might be cases/machines where Statistics`Library`ConstantVectorQ[#] && #[[1]] == 0 & wins.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.