www.gusucode.com > optim 案例源码 matlab代码程序 > optim/CompareAlgorithmsAndExamineSolutionProcessExample.m
%% Compare Algorithms and Examine Solution Process % Compare the results of fitting with the default % |'trust-region-reflective'| algorithm and the |'levenberg-marquardt'| % algorithm. Examine the solution process to see which is more efficient in % this case. %% % Suppose that you have observation time data |xdata| and observed response % data |ydata|, and you want to find parameters $x(1)$ and $x(2)$ to fit a % model of the form % % $$ \hbox{ydata} = x(1)\exp\left(x(2)\hbox{xdata}\right).$$ %% % Input the observation times and responses. % Copyright 2015 The MathWorks, Inc. xdata = ... [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]; ydata = ... [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5]; %% % Create a simple exponential decay model. fun = @(x,xdata)x(1)*exp(x(2)*xdata); %% % Fit the model using the starting point |x0 = [100,-1]|. x0 = [100,-1]; [x,resnorm,residual,exitflag,output] = lsqcurvefit(fun,x0,xdata,ydata); %% % Compare the solution with that of a |'levenberg-marquardt'| fit. options = optimoptions('lsqcurvefit','Algorithm','levenberg-marquardt'); lb = []; ub = []; [x2,resnorm2,residual2,exitflag2,output2] = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options); %% % Are the solutions equivalent? norm(x-x2) %% % Yes, the solutions are equivalent. % % Which algorithm took fewer function evaluations to arrive at the % solution? fprintf(['The ''trust-region-reflective'' algorithm took %d function evaluations,\n',... 'and the ''levenberg-marquardt'' algorithm took %d function evaluations.\n'],... output.funcCount,output2.funcCount) %% % Plot the data and the fitted exponential model. times = linspace(xdata(1),xdata(end)); plot(xdata,ydata,'ko',times,fun(x,times),'b-') legend('Data','Fitted exponential') title('Data and Fitted Curve') %% % The fit looks good. How large are the residuals? fprintf(['The ''trust-region-reflective'' algorithm has residual norm %f,\n',... 'and the ''levenberg-marquardt'' algorithm has residual norm %f.\n'],... resnorm,resnorm2)