user3086949
user3086949

Reputation: 21

Alternative way to loop for faster computing

Let's say I have a n*p dataframe.

I have computed a list of n matrix of p*p dimensions (named listMat in the R script belowed), in which each matrix is the distance matrix between the p variables for each of the n respondants.

I want to compute a n*n matrix called normMat, with each elements corresponding to the norm of the difference between each pairwise distance matrix. For exemple : normMat[1,2] will be the norm of a matrix named "diffMat" where diffMat is the difference between the 1st distance matrix and the 2nd distance matrix of the list of Matrix "listMat".

I wrote the following script which works fine, but i'm wondering if there is a more efficient way to write it, to avoid the loops (using for exemple lapply, etc ..) and make the script execution go faster.

# exemple of n = 3 distances matrix between p = 5 variables
x <- abs(matrix(rnorm(1:25),5,5))
y <- abs(matrix(rnorm(1:25),5,5))
z <- abs(matrix(rnorm(1:25),5,5))

listMat <- list(x, y, z)
normMat <- matrix(NA,n,n)

for (numRow in 1:n){
  for (numCol in 1:n){
    diffMat <- listMat[[numRow]] - listMat[[numCol]]
    normMat[numRow, numCol] <- norm(diffMat, type="F")
  }  
}

Thanks for your help.

Upvotes: 2

Views: 157

Answers (1)

TWL
TWL

Reputation: 2300

Try:

normMat <- function(x, y) {
    norm(x-y, type="F")
}

sapply(listMat, function(x) sapply(listMat, function(y) normMat(x,y)))

Upvotes: 2

Related Questions