MATLAB: How to compare each four rows by each other

compare rowscomparisonrows

Hello,
Suppose we have 8 rows where each element in a row is either zero or one. I want to compare rows to count differences in this way:
row1 with row2 ; row1 with row 3; row1 with row4; row2 with rows 3; row2 with row4; row3 with row4.
So how can I do that in repetition manner to repeat doing that for row5,6,7, and 8 together. note that the number of different elements between any two rows should be stored in a matrix where in our case here we should have 6 rows in the differences matrix where each row store the number of differences between two rows in the main matrix.
Regards,

Best Answer

If you have the Statistics and Machine Learning Toolbox, use the pdist (link) function, specifying the 'hamming' distance measure:
data = randi([0 1], 8, 5) % Create Data
d = pdist(data, 'hamming');
DistancesP = squareform(d) % Percentage Differences
DistancesA = squareform(d) * size(data,2) % Number Of Elements That Differ
produces:
data =
1 1 1 1 0
0 0 1 0 0
0 0 1 0 0
0 0 0 1 0
0 1 1 1 1
0 0 0 0 1
1 0 1 1 1
1 0 0 1 1
DistancesA =
0 3 3 3 2 5 2 3
3 0 0 2 3 2 3 4
3 0 0 2 3 2 3 4
3 2 2 0 3 2 3 2
2 3 3 3 0 3 2 3
5 2 2 2 3 0 3 2
2 3 3 3 2 3 0 1
3 4 4 2 3 2 1 0