MATLAB: How to compute Spearman’s rank correlation excluding specific values

correlationrankspearman

Hello,
I have two matrices A and B (both 20×20) 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?

Best 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));