# Counting the number of instances where items at the same position in two matrices are equal?

Given two matrices having the same dimensions:

m1 = {{1, a, 2}, {4, 5, 0}, {g, a, d}}
m2 = {{1, b, 2}, {7, 2, 0}, {a, a, a}}


Is there a built-in function that can return a count count for the number of instances where two entries in the same matrix position are equal? In the above example, for instance, we would have count = 4.

Note that, because I need to have a mix of numerical and string values in each matrix, I can't simply subtract the two matrices and look for non-zero positions. I'd also like to have 0 valued items in either matrix.

• Byt why not m1 - m2 // N // Count[#, 0., {2}] &
– Kuba
Oct 11, 2014 at 7:32
• closely related
– Kuba
Oct 11, 2014 at 7:39
• The built-in function you are looking for is Count. Apply it like so: Count[m1 - m2, 0 | 0., {2}] Oct 11, 2014 at 7:59

Not sure if this as simple as you're hoping, but:

Count[MapThread[SameQ, {m1, m2}, 2], True, 2]


would work.

"a" - "a"


0

Therefore

Count[Flatten[m1 - m2], 0]


4

m1 = {{-1., a, 2}, {4, 5, 0}, {g, a, d}};
m2 = {{-1., b, 2}, {7, 2, 0}, {a, a, a}};

Count[Flatten[m1 - m2], 0 | 0.]


4

• But 1. - 1. == 0.
– Kuba
Oct 11, 2014 at 7:34
• Count[m1 - m2, 0 | 0., {2}] (variant of Kuba comment made to the question) might be an improvement. Oct 11, 2014 at 7:51

Following How to find the distance of two lists? if your arrays are numeric this is much faster:

count[m1_, m2_] := Times @@ Dimensions[m1] - Total[Unitize @ Subtract[m1, m2], -1]


For an explanation of why Subtract is written out see:

### Timings:

{m1, m2} = List @@ RandomInteger[9, {2, 3000, 4000}];

Count[MapThread[SameQ, {m1, m2}, 2], True, 2] // Timing
Count[Flatten[m1 - m2], 0 | 0.]               // Timing
count[m1, m2]                                 // Timing

{3.198021, 1199603}

{1.248008, 1199603}

{0.046800, 1199603}

{a, b} = Dimensions[m1];

Count[Table[m1[[i, j]] === m2[[i, j]], {i, a}, {j, b}], True, 2]


4

• This is effectively the same as nikie's method but without leveraging Mathematica's array operations (i.e. MapThread); it is therefore several times slower. (14.1 seconds on the test in my answer.) Oct 11, 2014 at 17:05
• @Mr.Wizard I'm still fairly new to programming. Please forgive me if my answer is slow. Oct 11, 2014 at 19:12

If you wanted to know what elements as well as count:

{#, Length@#} &@(# -> Extract[m1, #] & /@ Position[N[m1 - m2], 0.])


gives: {{{1, 1} -> 1, {1, 3} -> 2, {2, 3} -> 0, {3, 2} -> a}, 4}