useryk useryk - 2 months ago 14
R Question

Matrix multiplication over three lists of matrices using apply() in R?

I am trying to do matrix multiplication over three lists of matrices, using apply() or something alike.

Here are the sample data:

mat1 <- matrix(c(1:16), 4, 4, byrow = TRUE)
mat2 <- matrix(c(1:16), 4, 4, byrow = TRUE)
mat3 <- matrix(c(1:16), 4, 4, byrow = TRUE)

l1 <- list(mat1, mat2, mat3)
l2 <- list(mat1, mat2, mat3)
l3 <- list(mat1, mat2, mat3)


I'd like to do the following and dump them into a new list, for each corresponding [[n]] in all three lists:

l1[[1]] %*% l2[[1]] %*% l3[[1]]
l1[[2]] %*% l2[[2]] %*% l3[[2]]
l1[[3]] %*% l2[[3]] %*% l3[[3]]


I tried the following:

mat <- lapply(c(mat1, mat2, mat3), function(x) x[1] %*% x[2] %*% x[3])


But I am not getting what I need. Please help?

Answer

I suggest using the following:

mat1 <- matrix(c(1:16), 4, 4, byrow = TRUE)
mat2 <- matrix(c(1:16), 4, 4, byrow = TRUE)
mat3 <- matrix(c(1:16), 4, 4, byrow = TRUE)

l1 <- list(mat1, mat2, mat3)
l2 <- list(mat1, mat2, mat3)
l3 <- list(mat1, mat2, mat3)

f <- function (...) Reduce("%*%", list(...))
mapply(f, l1, l2, l3, SIMPLIFY = FALSE) 

#[[1]]
#      [,1]  [,2]  [,3]  [,4]
#[1,]  3140  3560  3980  4400
#[2,]  7268  8232  9196 10160
#[3,] 11396 12904 14412 15920
#[4,] 15524 17576 19628 21680
#
#[[2]]
#      [,1]  [,2]  [,3]  [,4]
#[1,]  3140  3560  3980  4400
#[2,]  7268  8232  9196 10160
#[3,] 11396 12904 14412 15920
#[4,] 15524 17576 19628 21680
#
#[[3]]
#      [,1]  [,2]  [,3]  [,4]
#[1,]  3140  3560  3980  4400
#[2,]  7268  8232  9196 10160
#[3,] 11396 12904 14412 15920
#[4,] 15524 17576 19628 21680

The good point is that it does not matter how many lists you feed to mapply. For example,

mapply(f, l1, l2, l3, l1, l3, l3, SIMPLIFY = FALSE)

works, too. That is the magic power of Reduce and ....

Comments