Search code examples
matlabpearson-correlation

MATLAB: Fast correlation computation for all indices in 2 vectors


I have 2 vectors A and B, each of length 10,000. For each of ind=1:10000, I want to compute the Pearson's correlation of A(1:ind) and B(1:ind). When I do this in a for loop, it takes too much time. parfor does not work with more than 2 workers in my machine. Is there a way to do this operation fast and save results in a vector C (apparently of length 10,000 where the first element is NaN)? I found the question Fast rolling correlation in Matlab, but this is a little different than what I need.


Solution

  • You can use this method to compute cumulative correlation coefficient:

    function result = cumcor(x,y)
        n = reshape(1:numel(x),size(x));
        sumx = cumsum(x);
        sumy = cumsum(y);
        sumx2 = cumsum(x.^2);
        sumy2 = cumsum(y.^2);
        sumxy = cumsum(x.*y);
        result = (n.*sumxy-sumx.*sumy)./(sqrt((sumx.^2-n.*sumx2).*(sumy.^2-n.*sumy2)));
    end