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.
3 Answers
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}
];
TableForm[results,
TableHeadings -> {{"Exact zeros", "Numerical zeros", "Exact sparse",
"Numerical sparse", "Exact random",
"Numerical random"}, {"Linear Algebra method",
"Statistics method", "Total"}}]
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.
You can try the following
AA = {{0, 0}, {0, 0}};
AllTrue[Flatten[AA], PossibleZeroQ]
Total
? $\endgroup$LinearAlgebra`Private`ZeroArrayQ
? I recall that we had a similar question not long ago... $\endgroup$Total@matrix
returns a vector rather than a scalar. Even if youFlatten
the matrix first, you would also need to useAbs
to ensure that a zero result indicated that the matrix was all zeroes. $\endgroup$Total
would work but I'm interested in speed. It might be the fastest but I don't know. $\endgroup$