Instantly share code, notes, and snippets.

# jooh/QT_parCorrVsRegression.m Last active May 4, 2016

Matlab demo of relationship between partial correlation and multiple regression
 function QT_parCorrVsRegression % QT_parCorrVsRegression.m % When comparing a reference RDM to a candidate RDM, we might want to % partial out the contribution of another RDM on the correlation between % the candidate and the reference RDMs. % this could be done via partial correlations or linear regression. % this scripts demonstrates that the two approaches are identical. % clear;clc;close all %% control parameters nCond = 72; nVox = 100; %% simulating the RDMs rdm_ref = pdist(randn(nCond,nVox))'; rdm_cand1 = pdist(randn(nCond,nVox))'; rdm_cand2 = pdist(randn(nCond,nVox))'; %% partial correlation r1 = partialcorr(rdm_ref,rdm_cand1,rdm_cand2); fprintf('partial correlation coefficient = %.3f \n',r1) % for understanding it's better to code it up yourself: % z score so linear fit is equivalent to pearson r rdm_ref_z = zscore(rdm_ref); rdm_cand1_z = zscore(rdm_cand1); rdm_cand2_z = zscore(rdm_cand2); % remove the fitted contribution of cand2 from data and cand1 projectout = @(y,c) y - (c * (c \ y)); rdm_cand1_zp = projectout(rdm_cand1_z,rdm_cand2_z); rdm_ref_zp = projectout(rdm_ref_z,rdm_cand2_z); % now partial r is r1_alt = rdm_cand1_zp \ rdm_ref_zp; fprintf('partial correlation coefficient (alt) = %.3f \n',r1) % from the above it becomes pretty obvious that the reason why the below % might not produce similar results is that you haven't Z-scored the % predictors and data. %% linear regression % regress-out rdm2 from the reference rdm b1 = regress(rdm_ref,rdm_cand2); % you use b before defined here. Not sure if you were planning to use b or % b1. Assume b1. res_ref = rdm_ref-b1*rdm_cand2; % regress-out rdm2 from the candidate rdm b = regress(rdm_cand1,rdm_cand2); res_cand = rdm_cand1-b*rdm_cand2; r2 = corr(res_cand,res_ref); fprintf('regression-based results = %.3f \n',r2)

### spike3600 commented May 3, 2016

 interestingly, zscoring does not affect the linear correlation between two vectors. I'm now curious about rank correlations!
Owner Author

### jooh commented May 4, 2016

 Zscoring can't have an effect on correlation, because that operation is already performed as part of the correlation formula. Z-scoring an already standardised variable has no effect. Similarly, rank correlation can be thought of as a linear fit on the Z-scored ranks. Z-scoring the data before ranking will not change anything since Z-scoring cannot change the rank order of the data. Z-scoring after ranking is exactly what spearman rho is already doing.