5

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257

5 Answers5

4

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

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

would work.

Niki Estner
  • 36,101
  • 3
  • 92
  • 152
4
"a" - "a"

0

Therefore

Count[Flatten[m1 - m2], 0]

4

Update thanks to comments

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

eldo
  • 67,911
  • 5
  • 60
  • 168
4

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}

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2
{a, b} = Dimensions[m1];

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

4

konji
  • 21
  • 3
  • 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.) – Mr.Wizard Oct 11 '14 at 17:05
  • @Mr.Wizard I'm still fairly new to programming. Please forgive me if my answer is slow. – konji Oct 11 '14 at 19:12
1

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}

ubpdqn
  • 60,617
  • 3
  • 59
  • 148