0

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?

JoeLiBuDa
  • 219
  • 2
  • 10

2 Answers2

3

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
Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
1

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.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
  • Thank you very much. It works but one gets a "out of memory exception" for large matrices. Using just corr is much more efficient. – JoeLiBuDa Jun 10 '15 at 16:15