How to compute Spearman's rank correlation excluding specific values?

Hello,
I have two matrices A and B (both 20x20) with data from 0 to 1 (some are tied). I want to compute Spearman's rank correlation, but I don't want to include those values which in both matrices are equal to 0 (e.g. A(3,2) and B(3,2) are 0). How can I do that?

2 Comments

What correlations do you want? Between corresponding columns of A & B (20 correlations), or all possible pairs of columns (400 correlations)?
One correlation between matrices. I will transpose each matrix into one column containing 400 values to compute correlation, I just wanted to mention that initially I own data as a matrix (if this might be helpful).

Sign in to comment.

 Accepted Answer

% Set seed for reproducibility
rng default
% Make up some pretend data
N = 20;
A = binornd(1,0.50,N,N);
B = binornd(1,0.50,N,N);
% Find the locations that should be included from the correlation
inclusionIndex = not((A==0) & (B==0));
R = corr(A(inclusionIndex),B(inclusionIndex));

More Answers (1)

ix=(A>0) & (B>0);
A=A(ix);
B=B(ix);
Do whatever with A, B; they will be returned as column vectors by the logical addressing operation.

2 Comments

Your solution looks reasonably, however it is not working. If I have two matrices: A=[2 1 4;3 5 0; 1 9 0]; B=[1 2 5;7 9 0; 5 3 1]; and convert them your way, I get: A=[2;3;1;1;5;9;4], B=[1;7;5;2;9;3;5] - it deletes also last pair (with values 0 in A and 1 in B), what, to be honest, is quite surprising (like 0 was bigger than 0..). But thanks for help!
Oops! My bad, sorry. It's an OR condition between the two logicals--you want to keep the position if either is >0; the AND keeps only if both are the same.
>> ix=(A>0) | (B>0);
>> [A(ix) B(ix)]
ans =
2 1
3 7
1 5
1 2
5 9
9 3
4 5
0 1
>>

Sign in to comment.

Asked:

on 9 Aug 2017

Commented:

dpb
on 11 Aug 2017

Community Treasure Hunt

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

Start Hunting!