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]yieldsTrueife1contains 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. – corey979 Jan 17 '17 at 23:48Count[d2, 0, Infinity]if all you want is whether the array contains0. If you also are interest in0., useCount[d2, (0 | 0.), Infinity]. – bbgodfrey Jan 18 '17 at 00:19Total[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) – Felix Jan 18 '17 at 00:24Total[d2, Infinity]==0gives even better performance. – Felix Jan 18 '17 at 00:32MemberQ[d3, Except[0], {-1}]only checks for non-zero elements, but it is slower thanTotal. – bbgodfrey Jan 18 '17 at 00:56