Reputation: 1159
I have the following program. I just want to run the for loop and save the results from each iteration into valg[i,]
, valo[i,]
and obj[i,]
matrix/table
I'm doing something incorrectly, I get the following error
Error in `[<-`(`*tmp*`, i, , value = c(80.6413039191413, 40.0368791515846, :
subscript out of bounds
This program requires DEoptim package
I would greatly appreciate any help
g = matrix(c(1,6,1,1,1/6,
1/6,1,6,1,1,
1,1/6,1,6,1,
1,1,1/6,1,6,
6,1,1,1/6,1
), nrow=5, ncol=5)
a <- t(g)
lsm <- function(x){
b <- a - outer(x,x,`/`)
z <- sum(b^2)
return(z)}
for (i in (1 : 10)){
outDEoptim <- DEoptim(lsm, lower = rep(0.001,nrow(a)),
upper = rep(100,nrow(a)),DEoptim.control(trace = FALSE))
valg[i,] = rbind(outDEoptim$member$bestmemit[200,]) ## Save for each itr i and input to optim below for each itr
lsmoptl <- optim(par=c(valg[i,]), fn=lsm, gr = NULL,
method = c("L-BFGS-B"))
valo[i,] = lsmoptl$par/sum(lsmoptl$par) ## Save for each itr i
obj[i,] = lsmoptl$value ## Save for each itr i
}
Upvotes: 0
Views: 170
Reputation: 21433
Unless you forgot to post them and it is not the problem, you have to first initialize the object valg (and the others) for it to allow storing in indices.
For instance:
valg <- matrix(1, nrow=10, ncol=3)
will initialize the object.
From then on you can store in it using a loop.
for (i in 1:10) {
valg[i, ] <- 1:3
}
You may want to read some R tutorials online before posting elementary R issues.
Upvotes: 1