[英]How to use a for-loop within a for-loop in R
I'm kind of new to R, but I've got some experience with Java. 我对R有点陌生,但是我对Java有一定的经验。 In Java I used to code with for-loops in other for-loops, but I've noticed that this doesn't work the same way in R. 在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]
}
}
I want to walk through the second for-loop for every matrix-multiplication which is done in the first for-loop. 我要遍历在第一个for循环中完成的每个矩阵乘法的第二个for循环。 I've tried several things without the result I wished for and I hope that someone can help me out with this. 我已经尝试了好几种方法,但都没有达到我想要的结果,我希望有人可以帮助我解决这个问题。
First of all, as far as I understand, e
is 1x11 matrix, so looping through it with index 2:24 is weird. 首先,据我了解, e
是1x11矩阵,因此以索引2:24循环遍历是很奇怪的。
Secondly, since it's a single row on numbers, then sum()
work, don't need to loop through it. 其次,由于它是数字的一行,所以sum()
有效,不需要循环遍历。
for(i in 1:240){
e <- vector %*% (Matrix %^% i)
cumulativeSum <- cumulativeSum + sum(e)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.