MATLAB: How to compute linear correlation coefficient for the input faster than CORR using Statistics Toolbox 7.3 (R2010a)

corrfunctionisMATLABslowspeedupwhich

I am executing a code which makes hundreds of calls to CORR. I call CORR once on a large matrix to compute Pearson's linear correlation coefficient (default) as follows:
load returns
tic
ret_corr1 = corr(returns,'type','Pearson');
toc
Elapsed time is 0.081229 seconds.
When I execute the function hundreds of times, the overall time taken is extremely large.

Best Answer

This enhancement has been incorporated in Release 2011a (R2011a). For previous product releases, read below for any possible workarounds:
The following two workarounds allow you to compute the Pearson's linear correlation coefficient faster than CORR.
Workaround 1:
tic
ret_cov = cov(returns);
[~,ret_corr2] = cov2corr(ret_cov);
toc
Elapsed time is 0.009861 seconds.
Workaround 2:
tic
n = size(returns,2);
N = size(returns,1);
ret_corr3 = zeros(n,n);
for ix = 2:n
for iy = 1:ix-1
xm = returns(:,ix);
xmsx = (xm-mean(xm))./std(xm);
ym = returns(:,iy);
ymsy = (ym-mean(ym))./std(ym);
ret_corr3(ix,iy) = (1/(N-1))*sum(xmsx.*ymsy);
end
end
ret_corr3 = ret_corr3 + ret_corr3' + eye(n);
toc
Elapsed time is 0.016819 seconds.