How to create a matrix with the data of a comparison, upper triangular the percentage of similarity and lower triangular the times that were compared?

2 views (last 30 days)
I have a matrix with N rows and 4 columns. Each row represent a comparison of a file between different sources, columns represent the sources, each of the elements of the matrix can take values form 1-4 or NaN.
Column 1 have values of 1 or NaN
Column 2 have values of 1,2 or NaN
Column 3 have values of 1,2,3 or NaN
Column 4 have values of 1,2,3,4 or NaN
An example is:
M = [1 NaN 3 3;
1 2 NaN 2;
NaN 2 2 4;
1 2 1 1;
1 1 3 1;
1 1 3 4]
For example in row 1
[1 NaN 3 3]
sources 3 and 4 are similar, in source 2 there is not data, and source 1 is no similar to any other.
If I compare of M, source 1 with source 2 it was compared 4 times (because of NaN in M(1,2) and M(3,1)) and the similarity is 50% (2/4)
I would like to have a square matrix (4x4) with this data where the upper triangular matrix is the percentage of similarity and the lower triangular matrix the times that were compared, like this:
0 50* 25 40
4* 0 25 40
4 4 0 40
5 5 5 0
The stars are for the example when I compared source 1 with source 2 (indexes (1,2) and (2,1)).
I did that using a lot of IF and the script looks so ugly haha, "If" you can recomend me something I would really appreciate it

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 29 Jun 2016
a = permute(M,[3,2,1]);
b = permute(M,[2,3,1]);
x = sum(bsxfun(@eq,a,b),3);
y = sum(~isnan(bsxfun(@plus,a,b)),3);
out = tril(y,-1) + triu(x./y'*100,1);

More Answers (0)

Categories

Find more on Descriptive Statistics in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!