1
$\begingroup$

I'm trying to find a way to count the number of rows in a matrix that contains specific elements in specific cells.

For example, suppose I have the following matrix

Data={{1,1,1,1},{1,1,0,1},{1,0,0,1},{0,1,0,0},{1,0,0,0},{1,0,1,0},{1,1,1,1},{0,1,0,0}}

What I want to find is the number of rows that is consistent with the following list:

list1={1,Null,Null,1}

So, in the data, {{1,1,1,1},{1,1,0,1},{1,0,0,1},{1,1,1,1}} is consistent with the list1, so the output should be 4.

Another example is if list2={1,1,1,1}, then the output should be 2. If list3={1,Null,Null,Null}, then we should have 6 as there are 6 rows starting with 1.

How can this situation be efficiently programmed? The length of each row is the same in the data and I have a very large size of the zero-one matrix.

$\endgroup$
1
  • $\begingroup$ Just to add to the answers below: you can do strict filtering with Alternatives (|) and Repeated[] e.g. Count[{{1, 1, 1, 1}, {1, 1, 0, 1}, {1, 0, 0, 1}, {0, 1, 0, 0}, {1, 0, 0, 0}, {1, 0, 1, 0}, {1, 1, 1, 1}, {0, 1, 0, 0}}, {1, Repeated[0 | 1, {2}], 1}] $\endgroup$ Commented Apr 22, 2020 at 3:10

2 Answers 2

1
$\begingroup$
list1={1,Null,Null,1}
sel = Map[If[# === Null, __, #] &, list1];
Cases[Data, sel]

Mathematica graphics

list2 = {1, 1, 1, 1};
sel = Map[If[# === Null, __, #] &, list2]
Cases[Data, sel]

Mathematica graphics

list3 = {1, Null, Null, Null};
sel = Map[If[# === Null, __, #] &, list3]
Cases[Data, sel]

Mathematica graphics

$\endgroup$
1
$\begingroup$
data = {{1, 1, 1, 1}, {1, 1, 0, 1}, {1, 0, 0, 1}, {0, 1, 0, 0}, {1, 0,0, 0}, {1, 0, 1, 0}, {1, 1, 1, 1}, {0, 1, 0, 0}};

Cases[data, {1, _, _, 1}] // Length
(* 4 *)

Cases[data, {1, 1, 1, 1}] // Length
(* 2 *)

Cases[data, {1, _, _, _}] // Length
(* 6 *)
$\endgroup$
1
  • 2
    $\begingroup$ You can use Count[] instead of Length[Cases[(* stuff *)]]. $\endgroup$ Commented Apr 22, 2020 at 3:10

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.