我对optim函数不是很熟悉,我想从其结果中获取这些信息:a)要获得结果,需要进行多少次迭代? b)绘制部分解的序列,即在每次迭代结束时获得的解.
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?
预先感谢
推荐答案您可以修改函数以将传递给它的值存储到全局列表中.
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")现在,如果您在运行函数后检查i和val,可以看到发生了什么.如果您想在optim运行时查看这些值,则也向该函数中添加一条print语句.
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.
更多推荐
从R的optim函数获取更多详细信息
发布评论