Curve fitting for non-linear data

11 views (last 30 days)
Julian
Julian on 11 Oct 2018
Commented: Alex Sha on 29 Jan 2022
I am trying to fit some data using lsqcurvefit in MATLAB but I am fairly new to this area.
xdata1 = [0 60 660 1250];
ydata1 = [0 18 23 31];
In the image below, the red line is the fit I want to achieve. Sadly, Polyfit does not provide suitable results.
How can I achieve this fit? Thank you in advance!

Accepted Answer

Matt J
Matt J on 11 Oct 2018
I believe piece-wise linear fitting was in the scope of Bruno's free-knot spline fitting package,
  1 Comment
Julian
Julian on 12 Oct 2018
Thank you Matt I will look into this!

Sign in to comment.

More Answers (2)

Chaoyu Zhang
Chaoyu Zhang on 11 Oct 2018
Edited: Chaoyu Zhang on 15 Oct 2018
You can use the method described below,
The target equation (3rd order or maybe higher) is
y = a*x.^3 + b*x.^2 + c*x + d;
A * p = y;
p is the parameters of the equation,
p = [a;b;c;d]
A is the matrix made of x.^3,x.^2,x,1,
A = [x(1).^3 x(1).^2 x(1) 1; ... ; x(n).^3 x(n).^2 x(n) 1]
y is the vector made of y,
y = [y(1); ... ;y(n)];
p = (A.'*A)^(-1)*A.'*y;
Now you get the parameters you need.
  5 Comments
Matt J
Matt J on 15 Oct 2018
Here is a test showing the increased error sensitivity of inv(A.'*A)*(A.'*y).
N=1000;
M=15;
A=vander(linspace(1,3.3,M)) + eye(M);
xt=rand(M,1);
yt=A*xt;
y=yt+randn(M,N)*1e-6;
x1=inv(A.'*A)*(A.'*y);
x2=A\y;
Error1=mean( sqrt(sum((x1-xt).^2)) )
Error2=mean( sqrt(sum((x2-xt).^2)) )
should give something like
Error1 =
5.0094
Error2 =
2.8313e-04

Sign in to comment.


Image Analyst
Image Analyst on 11 Oct 2018
You cannot get that unless you put in a model curve for that shape. Otherwise functions are not going to know that it's a piecewise linear fit or some sharply kinked log function or whatever. And having more data points would help too. Then you can use fitnlm.
I'm attaching several examples for piecewise linear fit and non-linear fits.
  4 Comments
Alex Sha
Alex Sha on 29 Jan 2022
For three order of polyfit: y = p1+p2*x+p3*x^2+p4*x^3
Root of Mean Square Error (RMSE): 5.67944047963309E-15
Sum of Squared Residual: 1.2902417664678E-28
Correlation Coef. (R): 1
R-Square: 1
Parameter Best Estimate
---------- -------------
p1 3.92787554473843E-15
p2 0.340654276995852
p3 -0.000698994200659206
p4 3.57048623250019E-7
while, if taking function as: y = p1*x/(p2+x)^2-p3*x
Root of Mean Square Error (RMSE): 0
Sum of Squared Residual: 0
Correlation Coef. (R): 1
R-Square: 1
Parameter Best Estimate
---------- -------------
p1 9035.3274708592
p2 119.630504666011
p3 -0.0199834390844168
Obviously, the second function should be more reasonable than 3rd polyfit.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!