Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pairwise Comparison of rows in a matrix

I have a simulation code that produces a binary matrix in matlab always with 10 rows but a varying number of columns.

For example here:

 1     0     0     0
 0     0     0     0
 0     1     0     0
 1     0     0     0
 1     0     0     0
 1     0     1     0
 0     0     0     1
 1     0     0     0
 0     0     0     0
 0     0     0     0

I want to do pairwise comparision between the rows to determine how many elements are different between the two rows, ultimately to create a 10x10 symmetric matrix with the number of differences between the rows. Eg. Row 1 compared with Row 2...and so on.

So the (1,2) element (as well as the 2,1 element) of this matrix would compare row 1 with row 2 and would be 1 in this case as there is only a single difference.

I know this could be done with lots of loop coding, however feel there is likely a simpler way that I do not know of.

How should this be accomplished?

like image 784
pinkrain1010 Avatar asked Oct 07 '22 11:10

pinkrain1010


1 Answers

Without any look you can do:

A=[1 0 1; 0 1 1; 1 1 1 ; 0 0 0];
A*(1-A)'+(1-A)*A'
ans =
 0     2     1     2
 2     0     1     2
 1     1     0     3
 2     2     3     0

What it says is that a is different than b iff a=1 and b=0, or a=0 and b=1, which is equivalent to a*(1-b)+b*(1-a).

Every entry in the result matrix holds the number of differences between rows (i,j). By performing matrix multiplication you calculate the above for every entry of any pair of rows, and sum up the results.

like image 102
Oli Avatar answered Oct 10 '22 03:10

Oli