在时间t-1按顺序将列表中的矩阵乘以向量(递归) [英] Sequentially multiply matrices from a list by a vector at time t-1 (recursively)

查看:0
本文介绍了在时间t-1按顺序将列表中的矩阵乘以向量(递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将矩阵列表相乘,按照它们在列表中出现的顺序,从矩阵1开始,乘以初始向量,然后递归;所以列表中的矩阵2乘以结果向量。我尝试了lapplymap的各种迭代,但无法向前投影并递归执行。更明确地说:A[[1]] % * % allYears[,1],然后是A[[2]] % * % allYears[,2],.....,A[[4]] % * % allYears[,4],这将产生"allYears"中的最后第5列。以下是在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的索引,然后循环该索引的序列,根据该序列提取‘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

这篇关于在时间t-1按顺序将列表中的矩阵乘以向量(递归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆