I'm using R, and I need to find the correlation between every row and column of matrix A and B (ex: the correlation between the 1st row of matrix A and 1st column of matrix B, 2nd row of matrix A and 1st column of matrix B, 2nd row of matrix A and 2nd column of matrix B, etc.)

I realized I can do this by doing




... until I get to the very last row of matrixA (matrixA has 17000 rows)

My question is, how do I do this faster without having to type in each command? In addition, the most important part, is how do I get the max and min correlation values of ALL the correlation values I will have calculated in this way?

Many thanks! T

  • $\begingroup$ just 'normalize' each row of A and column of B; (subtract sample mean, divide by sample standard deviation) then take the matrix product of the normalized matrices. done. $\endgroup$ – shabbychef Jun 27 '12 at 16:47
  • $\begingroup$ duh, I didn't read the fine manual. Just do corrs <- cor(t(A),B). Look at the help for cor. $\endgroup$ – shabbychef Jun 27 '12 at 17:07

cor does this for you:

A <- matrix(rnorm(1000*20),nrow=1000)
B <- matrix(rnorm(20*400),nrow=20)
ABcor <- cor(t(A),B)
| cite | improve this answer | |
  • $\begingroup$ how do you know what row and column of the 2 matrices produced this max correlation value? $\endgroup$ – Tracy Lu Jun 27 '12 at 19:11
  • 2
    $\begingroup$ try arrayInd(which.max(ABcor),.dim=dim(ABcor)) and ? which.max and ? arrayInd. $\endgroup$ – shabbychef Jun 27 '12 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.