Conjugate matrix correlations in R - how to get through all the pairs?

I have 13 matrices of various sizes that I would like to use in pair matrix correlations with a user-defined function (which calculates the coefficient Rv). The function takes two arguments (matrix1, matrix2) and produces a scalar (basically the multidimensional value of r). I would like to run the function on all possible pairs of matrices (78 correlations in total) and get a 13 by 13 matrix from the received Rv-values ​​with the names of 13 matrices in rows and columns. I was thinking of trying to do this by putting matrices in a list and using a double loop to traverse the elements of the list, but this seems very complicated. I cited the below example with dummy data below. Does anyone have any suggestions on how to approach this? Thanks in advance.

# Rv function  
Rv <- function(M1, M2) {  
    tr <- function(x) sum( diag(x) )   
    psd <- function(x) x %*% t(x)   
    AA <- psd(M1)  
    BB <- psd(M2)  
    num <- tr(AA %*% BB)  
    den <- sqrt( tr(AA %*% AA) * tr(BB %*% BB) )  
    Rv <- num / den  
    list(Rv=Rv, "Rv^2"=Rv^2)  
}  

# data in separate matricies  
matrix1 <- matrix(rnorm(100), 10, 10)  
matrix2 <- matrix(rnorm(100), 10, 10)  
# ... etc. up to matrix 13  

# or, in a list  
matrix1 <- list( matrix(rnorm(100), 10, 10) )  
rep(matrix1, 13) # note, the matrices are identical in this example   

# call Rv function  
Rv1 <- Rv(matrix1, matrix2)  
Rv1$Rv^2  

# loop through all 78 combinations?  
# store results in 13 by 13 matrix with matrix rownames and colnames?  
+3
source share
1

expand.grid(), apply(). , 1: 3, 1:13.

R> work <- expand.grid(1:3,1:3)
R> work
  Var1 Var2
1    1    1
2    2    1
3    3    1
4    1    2
5    2    2
6    3    2
7    1    3
8    2    3
9    3    3
R> apply(work, 1, function(z) prod(z))
[1] 1 2 3 2 4 6 3 6 9
R> 

.

+3

Source: https://habr.com/ru/post/1771739/


All Articles