如何在列表中计算所有矩阵的乘积(所有矩阵都是nxn),例如,
a1 <- list(); a2 <- list(); a3 <- list()
a1[[1]] <- matrix(c(1:25), byrow = T, ncol = 5)
a1[[2]] <- matrix(c(1:25), byrow = T, ncol = 5)
a2[[1]] <- matrix(c(1:25), byrow = T, ncol = 5)
a2[[2]] <- matrix(c(1:25), byrow = T, ncol = 5)
a3[[1]] <- matrix(c(1:25), byrow = T, ncol = 5)
a3[[2]] <- matrix(c(1:25), byrow = T, ncol = 5)
a <- list(a1, a2, a3)
a1[[1]]%*%a1[[2]]%*%a2[[1]]%*%a1[[2]]%*%a3[[1]]%*%a3[[2]]
答案 0 :(得分:2)
如果它是单个list
Reduce(`*`, a)
如果有3个list
长度为1。
a1 <- list(a1)
a2 <- list(a2)
a3 <- list(a3)
Map(function(...) Reduce(`*`, list(...)), a1, a2, a3)
对于更新的帖子,
r1 <- Reduce(`%*%`, do.call(c, list(a1, a2, a3)))
r2 <- a1[[1]]%*%a1[[2]]%*%a2[[1]]%*%a2[[2]]%*%a3[[1]]%*%a3[[2]]
identical(r1, r2)
#[1] TRUE
set.seed(24)
a1 <- matrix(rnorm(25), ncol= 5)
a2 <- matrix(rnorm(25), ncol= 5)
a3 <- matrix(rnorm(25), ncol = 5)
a <- list(a1, a2, a3)