There are the functions lsqcurvefit (Optimization Toolbox) and nlinfit (Statistics Toolbox) that will fit an objective function you provide. They each have their own advantages and disadvantages, depending upon what you want to do.
If you don’t have those, using the MATLAB core function fminsearch can do the nonlinear fit with an additional line of code (the OLS cost function). (See the fminsearch documentation for details on what it does and how it works.)
This works:
y = @(b,x) b(1).*exp(-b(2).*x);
p = [3; 5]*1E-1;
x = linspace(1, 10);
yx = y(p,x) + 0.1*(rand(size(x))-0.5);
OLS = @(b) sum((y(b,x) - yx).^2);
opts = optimset('MaxFunEvals',50000, 'MaxIter',10000);
B = fminsearch(OLS, rand(2,1), opts)
figure(1)
plot(x, yx, '*b')
hold on
plot(x, y(B,x), '-r')
hold off
grid
Best Answer