I need a quick test to check if a large matrix contains any non-zeros. The Contains functions work on Lists not matrices.
d1 = ConstantArray[0, 100];
d2 = ConstantArray[0, {100, 100}];
ContainsOnly[d1, {0}]
ContainsOnly[d2, {0}]
ContainsAny[d1, {0}]
ContainsAny[d2, {0}]
(* True False True False *)
I know that I could use Flatten[], but Flatten appears to create another entire list in memory, which takes time and (worse) consumes memory:
n = 20000;
d2 = ConstantArray[0, {n, n}];
Print[Timing[ContainsOnly[Flatten@d2, {0}]]];
Print[Timing[d3 = Flatten[d2]][[1]]];
Print[Timing[ContainsOnly[d3, {0}]]];
(* {2.46, True} 1.375 {0.75, True} *)
Is there a way to just search the matrix instead of copying it into a Flatten[]'d list to search?
I ultimately just need to know if the matrix contains any non-zeros. Hopefully, there's a method that will stop search once it finds a non-zero.
ContainsOnly[e1,e2]
yieldsTrue
ife1
contains only elements that appear ine2
". Yourd2
- this is thee1
- is a list of lists of zeros - this list (the outer one) doesn't contain a0
-e2 == {0}
here - i.e.{0, ...., 0}
is not0
. You can simplyContainsOnly[Flatten@d2, {0}]
- yieldsTrue
. $\endgroup$Count[d2, 0, Infinity]
if all you want is whether the array contains0
. If you also are interest in0.
, useCount[d2, (0 | 0.), Infinity]
. $\endgroup$Total[Abs[d2], Infinity]
gives a similar performance of 2.5 s. If you have only positive numbers then you can gain performance by usingTotal[d2, Infinity]
(0.5 s) $\endgroup$Total[d2, Infinity]==0
gives even better performance. $\endgroup$