MATLAB: How to count identical elements in a non-symmetrical matrix

matrix

Suppose we have a binary, non-symmetrical, 4×4 matrix, like this one:
exercise = [ 0 1 1 0 ; 1 0 0 1 ; 0 0 0 1 ; 1 1 0 0]
What I would like to do is, I'd like to count the identical non-zero elements in it, meaning, after comparing the 1st row and the 1st column of this matrix, I'd like to see the total of overlapping elements. Let me show you an example.
1st row of the matrix: 0 1 1 0
1st column of the matrix: 0 1 0 1
1st element of the 1st row and 1st column: both zeros, but we are interested in the non-zero elements so we don't count this one. 2nd element of the 1st row and 1st column: both are ones. We are looking for such cases so we register this one. 3rd element of the 1st row is 1, 3rd element of 1st column is zero. They are not equal so we move on. Next: 4th element of the 1st row is zero, 4th element of the 1st column is 1. These are not equal either. To sum up, we can clearly see that the 2nd elements equal, so overall we have one non-zero element in common. Let's see the next example:
2nd row of the matrix: 1 0 0 1
2nd column of the matrix: 1 0 0 1
Here we have two equalling non-zero elements. Let's see the next:
3rd row: 0 0 0 1
3rd column: 1 0 0 0
Here we don't have any overlapping non-zero elements at all. Last but not least,
4th row: 1 1 0 0
4th column: 0 1 1 0
One non-zero element in common here. What would really be awesome if there was a way to list the count of matches, maybe like this:
(1) 1
(2) 2
(3) 0
(4) 1

Best Answer

>> x = [ 0 1 1 0 ; 1 0 0 1 ; 0 0 0 1 ; 1 1 0 0]
>> [[1:4].' sum(x.*x.',2)]
ans =
1 1
2 2
3 0
4 1
>>