Getting more details from optim function from R

artificial-intelligence, convex-optimization, r

Solution

You could modify your function to store the values that are passed into it into a global list.

i <- 0  
vals <- list()
f1 <- function(x) {
  i <<- i+1
  vals[[i]] <<- x

  x1 <- x[1]
  x2 <- x[2]
  x1^2 + 3*x2^2  
}

res <- optim(c(1,1), f1, method="CG")

Now if you examine i and vals after you run the function you can see what happened. If you want to see the values while optim is running throw a print statement into the function as well.

Problem

I'm not very familiar with the optim function, and I wanted to get these informations from its results: a) how many iterations were needed for achieving the result? and b) to plot the sequence of partial solutions, that is, the solution obtained in the end of each iteration. My code until now looks like this: ``` f1 <- function(x) { x1 <- x[1] x2 <- x[2] x1^2 + 3*x2^2 } res <- optim(c(1,1), f1, method="CG") ``` How can I improve it to get further information? Thanks in advance

Original source