www.gusucode.com > optim 案例源码 matlab代码程序 > optim/BestFitWithBoundConstraintsExample.m
%% Best Fit with Bound Constraints % Find the best exponential fit to data where the fitting parameters are % constrained. %% % Generate data from an exponential decay model plus noise. The model is % % $$ y = \exp(-1.3t) + \varepsilon,$$ % % with $t$ ranging from 0 through 3, and $\varepsilon$ normally distributed % noise with mean 0 and standard deviation 0.05. % Copyright 2015 The MathWorks, Inc. rng default % for reproducibility xdata = linspace(0,3); ydata = exp(-1.3*xdata) + 0.05*randn(size(xdata)); %% % The problem is: given the data (|xdata|, |ydata|), find the exponential % decay model $y = x(1)\exp(x(2)\hbox{xdata})$ that best fits the data, % with the parameters bounded as follows: % % $$0\le x(1)\le 3/4$$ % % $$-2\le x(2)\le -1.$$ lb = [0,-2]; ub = [3/4,-1]; %% % Create the model. fun = @(x,xdata)x(1)*exp(x(2)*xdata); %% % Create an initial guess. x0 = [1/2,-2]; %% % Solve the bounded fitting problem. x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub) %% % Examine how well the resulting curve fits the data. Because the bounds % keep the solution away from the true values, the fit is mediocre. plot(xdata,ydata,'ko',xdata,fun(x,xdata),'b-') legend('Data','Fitted exponential') title('Data and Fitted Curve')