Question

I am writing a program that optimizes a function, and I need to assign a variable such that it can be used for the next iteration inside the function. This example is not reproducible, but it should show the general point:

gmmobjnoinst=function(theta2){

    deltanew <- innerloop(theta2,delta0)  #the thing using the input (delta0)
    delta0 <- deltanew                    #the thing I want to be saved for next iteration

    theta1hat <- solve(t(x1)%*%x1)%*%t(X)%*%deltanew
    w <- deltanew-x1%*%theta1hat


    gmmobj <- t(w)%*%w

    return(gmmobj)

}

Will the next iteration in the optimization:

optmodel3nevo=optim(approxstartingnevo,gmmobjnoinst,
    method="L-BFGS-B", hessian=TRUE,lower=c(0,0,0,0,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,
        -Inf,-Inf),upper=rep(Inf,13),
    control=list(maxit=20000, fnscale=1))

be using delta0 into the formula for deltanew ? What if I used <<- instead of <-? That seems like it MAY do what I want, but I am having a hard time checking..

Was it helpful?

Solution

You can do it this way:

gmmobjnoinst.make <- function(delta.ini){
   delta0 <- delta.ini

   gmmobjnoints <- function(theta2){

     deltanew <- innerloop(theta2,delta0)  #the thing using the input (delta0)
     delta0 <<- deltanew                    #the thing I want to be saved for next iteration

     theta1hat <- solve(t(x1)%*%x1)%*%t(X)%*%deltanew
     w <- deltanew-x1%*%theta1hat

     gmmobj <- t(w)%*%w

     return(gmmobj)
   }

   return(gmmobjnoints)
}

gmmobjnoinst <- mgmmobjnoinst.make(0)

This way delta0 becames an static variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top