我正在尝试将矩阵列表(按照它们在从矩阵 1 开始的列表中出现的顺序)乘以初始向量,然后递归;因此列表中的矩阵 2 乘以所得向量。我尝试了 lapply
和 map
的各种迭代,但无法向前投影并递归执行此操作。更明确地说:A[[1]] % * % allYears[,1]
,然后A[[2]] % * % allYears[,2],....., A[[4]] % * % allYears[,4]
生成 "allYears"
中的最后第五列。下面是示例代码,在 A[[i]]
索引处的 for 循环中存在已知错误,因为未显式引用 i
。
A <- lapply(1:4, function(x) # construct list of matrices
matrix(c(0, 0, 10,
rbeta(1, 5, 4), 0, 0,
0, rbeta(1, 10, 2), 0), nrow=3, ncol=3, byrow=TRUE, ))
n <- c(1000, 100, 10) # initial vector of abundances
nYears <- 4 # define the number of years to project over
allYears <- matrix(0, nrow=3, ncol=nYears+1) # build a storage array for all abundances
allYears[, 1] <- n # set the year 0 abundance
for (t in 1:(nYears + 1)) { # loop through all years
allYears[, t] <- A[[i]] %*% allYears[, t - 1]
}
最佳答案
根据描述,也许我们需要循环序列 - 即 A
的长度是 4
,而 'allYears' 的列数为 5。创建从 2 到 ncol
的索引'allYears',然后循环该索引的序列,根据序列提取'A'的相应元素,我们得到 allYears
上一栏
i1 <- 2:(nYears + 1)
for(t in seq_along(i1)) {
allYears[,i1[t]] <- A[[t]] %*% allYears[,i1[t]-1]
}
-输出
> allYears
[,1] [,2] [,3] [,4] [,5]
[1,] 1000 100.00000 817.24277 2081.08322 333.6702
[2,] 100 261.46150 55.44237 423.22095 1244.6680
[3,] 10 81.72428 208.10832 33.36702 355.5175
关于r - 在时间 t-1 处将列表中的矩阵按顺序乘以向量(递归地),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70790552/