2017-08-11 70 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