Difficulty in fitting two lines with polynomials
11 views (last 30 days)
Show older comments
Hi, I want to fit data which resembles two piecewise linear functions using polynomials.
Y=30000X for X<=0.001;
Y=27+3000X for 0.001<X<0.003.
When I use polyfit or cftool, the fitted curve has ups and downs (change of sign in curvature) which I don't want. I'm getting smooth curve when I use polynomials of the order 20 which is really high.
I would prefer a fitted curve without change in sign of curvature even at the expense of some accuracy (with lower orders of polynomials).
How can I do it?
Thanks, Deepesh.
1 Comment
Image Analyst
on 3 Dec 2014
Attach your data (so we can try things with it) and attach a screenshot so we can see what you're seeing.
Answers (2)
dpb
on 3 Dec 2014
Edited: dpb
on 3 Dec 2014
Piecewise linear regression is fairly easy to code anyway...the algebra to add the condition to match the two at the breakpoint is
y = a1 + b1 x, x<=c,
y = a2 + b2 x, x>c.
Match breakpoint, or a1 + b1 c = a2 + b2 c. Rearrange this to isolate (say) a2 as
a2 = a1 + b1 c - b2 c --> a1 + c(b1-b2) = aprime
Now have
y = a1 + b1 x, x<=c,
y = aprime + b2 x, x>c.
This is easy-peasy to code in Matlab and use as target for nlinfit --
function y=piecewise(coef,x)
% return piecewise linear fit given a1,b1,c,b2 as coefficient array and vector x
% c is breakpoint, a1 is intercept of first section, b1,b2 are two segment slopes
a1=coef(1); b1=coef(2); % reduce parentheses clutter....
c=coef(3); b2=coef(4);
ix=x>c; % location > breakpoint
y(ix)=[a1+c*(b1-b2)+b2*x(ix)];
y(~ix)=[a1+b1*x(~ix)];
y=y(:);
Use this as
coeff=nlinfit(X,Y,@piecewise,coeff0);
Example: for Hayden dataset
>> coeff=nlinfit(X,Y,@piecewise,[0 .01 1.5 0.1])
coeff =
-0.0077 0.0155 1.6804 0.1067
>>
0 Comments
dpb
on 1 Dec 2014
Classic piecewise regression problem...use some of the File Exchange tools...
2 Comments
dpb
on 3 Dec 2014
A cubic spline is a polynomial, just a particular form of one... :)
It would appear that the other link is a linear piecewise polynomial w/ specified knot location.
Do you want/need continuous first/second derivatives or simply only two slopes?
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!