This is comp sci 101 stuff, but I couldn't find an answer applicable to R (or matlab).
I have a for
loop that I want to initialize with a first guess (all zeros here, but maybe something else later), but I want to keep updating with each iteration. What I have below works, but it kind of clunky and embarrassing.
I would like to avoid the one iteration before the for
loop. I could do it with an ifelse
inside the loop, but that seems inefficient. Thanks!
alpha <- 0.3
beta <- 0.6
m <- 5 # elements in k
n <- 10 # iterations
k.prime <- v <- matrix(0, n, m)
k <- seq(from=0.04, to=0.2, length.out=m) # poss values for k
colnames(v) <- colnames(k.prime) <- round(k, digits=2)
# first loop for taking the first guess for v()
i <- 1
for (j in 1:m) {
temp.v <- log(k[j]^alpha - k) + beta*rep(0, times=m)
v[i, j] <- max(temp.v)
k.prime[i, j] <- k[which.max(temp.v)]
}
# remaining loops
for (i in 2:n) {
for (j in 1:m) {
temp.v <- log(k[j]^alpha - k) + beta*v[i-1, ]
v[i, j] <- max(temp.v)
k.prime[i, j] <- k[which.max(temp.v)]
}
}
v
k.prime