Corrcoef in Matlab is very slow

587 views Asked by At

I have the following code:

for k = 1:256
            for t = 1:10000
                % R matrix
                buffer = corrcoef(matrixA(:,k),matrixB(:,t));
                correlation_matrix(k,t)  = buffer (2,1);
            end
        end

I calculate the pearson correlation of the columns of two matrices. This works fine for me and the results are correct. However the process seems to be very very slow. Does anyone have an idea how to accelerate the calculations here?

2

There are 2 answers

0
Chris Taylor On BEST ANSWER

You can remove the loop entirely by using corr from the stats toolbox

>> matrixA = randn(100, 256);
>> matrixB = randn(100, 10000);
>> size(corr(matrixA, matrixB))
ans =

   256   10000
1
Sam Roberts On

Just concatenate the matrices, calculate all the correlations in one operation, and then extract the relevant ones.

>> matrixA = rand(100,256);
>> matrixB = rand(100,10000);
>> matrixC = [matrixA,matrixB];
>> c = corrcoef(matrixC);
>> correlation_matrix = c(1:256, 257:10256)

Should be quite a lot faster.