# Finding the correlation of every row and column between 2 matrices in R, then taking the max and min values

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

cor(matrixA[1,],matrixB)

cor(matrixA[1,],matrixB)

cor(matrixA[1,],matrixB)

... 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

• 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. – shabbychef Jun 27 '12 at 16:47
• duh, I didn't read the fine manual. Just do corrs <- cor(t(A),B). Look at the help for cor. – shabbychef Jun 27 '12 at 17:07

cor does this for you:
A <- matrix(rnorm(1000*20),nrow=1000)

• try arrayInd(which.max(ABcor),.dim=dim(ABcor)) and ? which.max and ? arrayInd. – shabbychef Jun 27 '12 at 19:22