简体   繁体   中英

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. 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.

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. 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.

Secondly, since it's a single row on numbers, then sum() work, don't need to loop through it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM