Estimating initial values for nlinfit or lsqcurvefit

6 views (last 30 days)
Janett Göhring on 7 Mar 2013
Hello,
I have a problem finding good initial values for nlinfit or lsqcurvefit.
y = [10000;8000;6000;5000;4000;3500;3000;2500;2000];
x = [36;86;154;203;273;318;371;439;521];
% alternative dataset
%y =[200,250,300,350,400,450,500,550,600,650,700,766];
%x =[618,546,481,413,354,300,255,207,164,127,89,43];
modelFun = @(p,x) p(1) - p(2)*x + p(3)*(x-p(4)).^2 - p(5)*(x-p(4)).^3;
% lsqcurvefit
paramEsts0 = lsqcurvefit(modelFun,[1 0.1 0.1 100 0.1],x,y);
paramEsts = lsqcurvefit(modelFun,paramEsts0,x,y)
% nlinfit
paramEstsLin0 = nlinfit(x, y, modelFun,[1 0.1 0.1 100 0.1]);
paramEstsLin = nlinfit(x, y, modelFun,paramEstsLin0)
xx = linspace(min(x), max(x));
yylsq = modelFun(paramEsts,xx);
yylin = modelFun(paramEstsLin,xx);
figure(1)
plot(x,y,'o', xx,yylin,'-' ,xx,yylsq,'-');
The initial values [1 0.1 0.1 100 0.1] are just values which I found to work for nlinfit (at least for the first dataset). I want to find an automatic way that both data-sets get fitted in an acceptable way without changing the starting points manually.
Any help is much appreciated!
Thanks! Janett

Tom Lane on 7 Mar 2013
If you expand out your expression, you'll see that you have a polynomial up to x^3, so there are four coefficients including the intercept. But you have specified five coefficients. Try this instead:
modelFun = @(p,x) p(1)*(x-p(4)) + p(2)*(x-p(4)).^2 + p(3)*(x-p(4)).^3;
p0 = [1 1 1 500];
Then use p0 as your initial values. You may find that both nlinfit and lsqcurvefit will have an easier time of it if you avoid trying to include the fifth (overdetermined) parameter. Then, if you like that, you can notice that you get the same results this way:
poly = polyfit(x,y,3);
line(x,polyval(poly,x),'color','c')
Your function is equivalent to a third-order polynomial, and it can be fit by linear least squares with no nonlinear fitting required.
Janett Göhring on 11 Mar 2013
Thanks! I was staring at that formula for 3 days and couldn't see that problem ... ^^