我需要将矩阵列表中子矩阵的每一列与一列相乘,然后按列加总。我可以通过for循环执行此操作,但列表可能包含1000多个子矩阵,这可能效率不高。将感谢任何有关矢量化版本的帮助。
install.packages(c("pracma"))
library(pracma)
### generate nested list
l1<-matrix(c(1:8),nrow=2)
l2<-matrix(c(4:11),nrow=2)
l3<-matrix(c(1:16),nrow=4)
l4<-matrix(c(6:21),nrow=4)
l<-list(l1,l2)
ll<-list(l3,l4)
lll<-list(l,ll)
lll
[[1]]
[[1]][[1]]
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
[[1]][[2]]
[,1] [,2] [,3] [,4]
[1,] 4 6 8 10
[2,] 5 7 9 11
[[2]]
[[2]][[1]]
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
[[2]][[2]]
[,1] [,2] [,3] [,4]
[1,] 6 10 14 18
[2,] 7 11 15 19
[3,] 8 12 16 20
[4,] 9 13 17 21
# multiply each column of matrices in lll by m
m1<-list(as.matrix(c(1:2)),as.matrix(c(3:4)))
m2<-list(as.matrix(c(5:8)),as.matrix(c(9:12)))
m<-list(m1,m2)
m
[[1]]
[[1]][[1]]
[,1]
[1,] 1
[2,] 2
[[1]][[2]]
[,1]
[1,] 3
[2,] 4
[[2]]
[[2]][[1]]
[,1]
[1,] 5
[2,] 6
[3,] 7
[4,] 8
[[2]][[2]]
[,1]
[1,] 9
[2,] 10
[3,] 11
[4,] 12
sum_k<-list()
sum_l_<-list()
for (l in 1:2){
for(k in 1:2){
sum=colSums(arrayfun('*',lll[[l]][[k]],m[[l]][[k]]))
sum_k[[k]]<-sum
}
sum_l_[[l]]<-sum_k
}
[[1]]
[[1]][[1]]
[1] 5 11 17 23
[[1]][[2]]
[1] 32 46 60 74
[[2]]
[[2]][[1]]
[1] 70 174 278 382
[[2]][[2]]
[1] 320 488 656 824