Least square curve fit

10 views (last 30 days)
anala reddy
anala reddy on 25 Aug 2017
Answered: Alex Sha on 9 Nov 2019
For function like y = a*(x-b)^c, how can I use the least square curve fit feature to find out the coefficients a, b and c? But If i use the custom equation in cftool it reports " Complex value computed by model function, fitting cannot continue. Try using or tightening upper and lower bounds on coefficients".

Answers (2)

Star Strider
Star Strider on 25 Aug 2017
I do not have the Curve Fitting Toolbox, so I cannot provide an exact example. However the problem is obvious — the complex values result from (x-b)<0, and -Inf at x=b. You need to constrain ‘b’ so that (x-b)>0. This requires b<x, so constrain ‘b’ to be less than ‘min(x)-1E-8’ (with the ‘1E-8’ preventing (x-b)=0). Set that as the upper bound of ‘b’.
  4 Comments
anala reddy
anala reddy on 27 Aug 2017
I have attached my data and script..
predicted = @(a,x) a(1)*((x-a(2)).^a(3));
a0 = [?:?:?];
[ahat,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(predicted,a0,x,y);
May i know how to set the initial value of a0 inorder to obtain the fit and extract the co-efficients a1,a2,a3...?
Star Strider
Star Strider on 27 Aug 2017
This works. It does not (in my opinion) produce a good fit, and only ‘a(1)’ is significantly different from zero. (Parameter confidence intervals that include zero are not needed in the model.) A logistic model might be a better fit, if it describes the system that produced your data.
data = load('nmoschar.txt');
x = data(:,1);
y = data(:,2);
predicted = @(a,x) a(1).*((x-a(2)).^a(3));
ub_a2 = min(x)-1E-8;
a0 = [sqrt(eps), max(x), 1.4];
[ahat,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(predicted,a0,x,y, [0,0,0]-1E-8, [Inf,ub_a2,Inf]);
ci = nlparci(ahat,residual,'jacobian',real(jacobian));
figure(1)
plot(x, y, 'pg')
hold on
plot(x, predicted(ahat,x), '-r')
hold off
It is necessary to constrain the parameters to avoid complex coefficients.
The nlparci function requires the Statistics and Machine Learning Toolbox.

Sign in to comment.


Alex Sha
Alex Sha on 9 Nov 2019
The function of lsqcurvefit use local optimization algorithm, so it is too weak on fault tolerance, try to use global optimization algorithms, easy to get proper result:
Root of Mean Square Error (RMSE): 1.89485474476935E-5
Sum of Squared Residual: 3.94952195415243E-9
Correlation Coef. (R): 0.99509458980833
R-Square: 0.990213242665809
Adjusted R-Square: 0.987766553332261
Determination Coef. (DC): 0.98908887287217
Chi-Square: 4.92331654510374E-5
F-Statistic: 348.803598712296
Parameter Best Estimate
---------- -------------
a 0.000558941792124118
b -9.85792530954279E-16
c 3.84941267720528

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!