MATLAB: Lsqcurvefit not finding best fit

lsqcurvefitMATLABOptimization Toolbox

I'm trying to fit a sin wave pulse, and I can't get lsqcurvefit (or nlinfit) to properly fit the start/stop times of the pulse. Here's the code I'm using:
f = @(a,t) a(1) + a(2).*sin(2*pi*a(3).*t + a(4)).*(t > a(5)/1000).*(t < a(6)/1000);
a0 = [4.806,1.1,1000,-2.43,5,40];
lb = [4,0, 990,-2*pi,0,1000*t(end)/2];
ub = [6,6,1010, 2*pi,1000*t(end)/2,1000*t(end)];
options = optimoptions('lsqcurvefit','TolX',1E-12,'TolFun',1E-12,'display','iter');
[a,resnorm,resid,exitflag,output,lambda,jacobian] = lsqcurvefit(f,a0,t,y,lb,ub,options);
plot(t,y,':',t,f(a,t),'-','LineWidth',2)
And here's the resulting output:
Norm of First-order
Iteration Func-count f(x) step optimality
0 7 7077.56 7.47e+06
1 14 6263.64 0.116348 651
2 21 6253.51 0.0151571 9.82
3 28 6253.51 0.000237627 0.00237
4 35 6253.51 6.05696e-08 3.65e-06
Local minimum possible.
lsqcurvefit stopped because the size of the current step is less than
the selected value of the step size tolerance.
a(5) and a(6) remain unchanged from the intial guess (5 and 40). Any tips on what I need to do to make this work?

Best Answer

You probably need to set larger finite differences on your a(5) and a(6) coefficients. Remember, lsqcurvefit is for differentiable functions, and your objective is not smooth in the a(5) and a(6) coefficients. See Optimizing a Simulation or ODE for a discussion about setting finite differences.
Alan Weiss
MATLAB mathematical toolbox documentation