5
$\begingroup$

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.

$\endgroup$
5
  • $\begingroup$ You could use Total? $\endgroup$
    – user27119
    Commented Oct 13, 2020 at 13:31
  • 2
    $\begingroup$ Maybe LinearAlgebra`Private`ZeroArrayQ? I recall that we had a similar question not long ago... $\endgroup$ Commented Oct 13, 2020 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$ Commented Oct 13, 2020 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
    Commented Oct 13, 2020 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$ Commented Oct 13, 2020 at 18:53

3 Answers 3

14
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

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}
   ];

TableForm[results, 
 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.

$\endgroup$
2
$\begingroup$

You can try the following

AA = {{0, 0}, {0, 0}};
AllTrue[Flatten[AA], PossibleZeroQ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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