2017-08-11 199 views
1

我使用lsqnonlin作为我的优化例程。我需要在每次迭代时绘制成本函数,同时显示以前的所有值。所以我想显示类似this使用lsqnonlin在所有迭代过程中绘制函数值演化

enter image description here

然而,使用lsqnonlin,我只能够在只有当前迭代绘制成本函数的值。使用这些选项:

options   = optimset('TolFun', 1e-5, 'TolX',1e-5, 'MaxFunEvals', 10000, 'PlotFcns', @optimplotfval,'Display','iter') 

有没有一种方法来设置lsqnonlin这样的选择,我得到类似上面显示图什么?

回答

2

如果你看看程序optimplotfval.m(MATLAB中的终端进入edit optimplotfval.m,你会看到下面的注释:那么

% STOP = OPTIMPLOTFVAL(X,OPTIMVALUES,STATE) plots OPTIMVALUES.fval. If 
% the function value is not scalar, a bar plot of the elements at the 
% current iteration is displayed. If the OPTIMVALUES.fval field does not 
% exist, the OPTIMVALUES.residual field is used. 

,例如,fminsearch你会得到目标/成本函数值的曲线图与迭代次数,但在lsqnonlin情况下,看来你是在给定的迭代中获得的剩余价值的柱状图。

一个修复程序来为的是让基于optimplotfval.m自己的绘图功能。复制粘贴optimplotfval.m到另一个文件,例如my_opt_plot.m然后更改剩余选项在程序的起始部分:

stop = false; 
switch state 
    case 'iter' 
     if isfield(optimValues,'fval') 
      if isscalar(optimValues.fval) 
       plotscalar(optimValues.iteration,optimValues.fval); 
      else 
       plotvector(optimValues.iteration,optimValues.fval); 
      end 
     else 
      % Plot the squared norm of residuals as a function of iteration number instead of bar plot of residual values at current iteration 
      fval = norm(optimValues.residual)^2; 
      % Call the scalar function instead 
      plotscalar(optimValues.iteration,fval);  
end 

你可以把这种新的功能,以同样的方式,你叫optimplotfval.m:在我的情况

options = optimoptions('lsqnonlin','Display','iter','PlotFcns',@my_opt_plot); 
[x,resnorm,residual,exitflag,output] = lsqnonlin(@simple_fun,xc0,[],[],options); 

simple_fun基于从MATLAB的doc条目lsqnonlin一个例子:

function f = simple_fun(xc) 
    x = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]; 
    y = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5]; 

    f = xc(1)*exp(xc(2)*x)-y; 
end 

如果用的人比较绘制的目标函数值PR在屏幕上,他们确实匹配。

+0

非常感谢,这正是我想要的。你不能希望得到比你更好,更准确的答案。 –

+0

很高兴能够提供帮助,您的问题很好,我将来可能需要解决方案:) – atru