%% Fit a Problem with Bound Constraints
% Find the best-fitting model when some of the fitting parameters have bounds.
% Find a centering b and scaling a that best fit the function
% a\exp(-t)\exp(-\exp(-(t-b)))
% to the standard normal density,
% \frac{1}{\sqrt{2\pi}}\exp\left(-t^2/2\right).
%
% Create a vector t of data points, and the corresponding normal density at those points.

t = linspace(-4,4);
y = 1/sqrt(2*pi)*exp(-t.^2/2);

%
% Create a function that evaluates the difference between the centered and scaled function from the normal y, with x(1) as the scaling a and x(2) as the centering b.

fun = @(x)x(1)*exp(-t).*exp(-exp(-(t-x(2)))) - y;

%
% Find the optimal fit starting from x0 = [1/2,0], with the scaling a between 1/2 and 3/2, and the centering b between -1 and 3.

lb = [1/2,-1];
ub = [3/2,3];
x0 = [1/2,0];
x = lsqnonlin(fun,x0,lb,ub)

%
% Plot the two functions to see the quality of the fit.

plot(t,y,'r-',t,fun(x)+y,'b-')
xlabel('t')
legend('Normal density','Fitted function')

% Copyright 2015 The MathWorks, Inc.