Difficulty in fitting two lines with polynomials
显示 更早的评论
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 个评论
Image Analyst
2014-12-3
Attach your data (so we can try things with it) and attach a screenshot so we can see what you're seeing.
回答(2 个)
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
>>
dpb
2014-12-1
1 个投票
Classic piecewise regression problem...use some of the File Exchange tools...
2 个评论
Deepesh upadrashta
2014-12-3
dpb
2014-12-3
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?
类别
在 帮助中心 和 File Exchange 中查找有关 Polynomials 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!