如何在 R 中的 for 循环中使用 for 循环

How to use a for-loop within a for-loop in R

我是 R 的新手,但我对 Java 有一些经验。在 Java 中,我曾经在其他 for 循环中使用 for 循环进行编码,但我注意到这在 R 中的工作方式不同。

p <- 11
diags <- list(rep(0.30, p), rep(0.45, p), rep(0.25, p)) 
Matrix <- as.matrix(bandSparse(p, k = -c(-1:1), diag = c(diags), symm=FALSE)) 
Matrix[1,1] <- 0.70
Matrix[11,11] <- 0.75

vector <- rep(0, 11)
vector[5] <- 1
vector

for(i in 1:240){
    e <- vector %*% (Matrix %^% i)
    for(j in 2:24){
        cumulativeSum <- cumulativeSum + e[j]
    }
}

我想为第一个 for 循环中完成的每个矩阵乘法遍历第二个 for 循环。我已经尝试了几件事,但没有得到我想要的结果,我希望有人能帮我解决这个问题。

首先,据我了解,e 是 1x11 矩阵,因此使用索引 2:24 遍历它很奇怪。

其次,因为它是数字的单行,所以sum()有效,不需要遍历它。

for(i in 1:240){
  e <- vector %*% (Matrix %^% i)
  cumulativeSum <- cumulativeSum + sum(e)
}