开发者

-- How to start a loop with a first guess?

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


Init v[1,] with zeroes, delete the first loop and fix i index to i+1 elsewhere.
This should then look like this:

alpha<-0.3
beta<-0.6
m<-5 #elements in k
n<-10 #iterations
k.prime<-matrix(0,n,m);
v<-matrix(0,n+1,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)


v[1,]<-rep(0,m);

# remaining loops
for(i in 1:n){
    for(j in 1:m){
        temp.v<-log(k[j]^alpha-k)+beta*v[i,]
        v[i+1,j]<- max(temp.v)
        k.prime[i,j]<-k[which.max(temp.v)]
    }
}
v[-1,]->v; #Cleanup of 0-row

v 
k.prime


Just do :

for (i in 1:n) {
    for (j in 1:m) {
        if (i == 1) 
            temp.v <- log(k[j]^alpha - k) + beta*rep(0, times=m)
        else
            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)]
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜