Add trendline and calculate slope of trendline
14 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a set of X and Y data. I plotted a scatter plot for these 2 sets. I would like to add a trendline for the scatter plot and calculate the slope of this trendline while forcing the intercept to = 0. Basically this can be done in excel, but I would like to add this into my code and automate the process. Is this possible? I intend to use values from the trendline equation for other calculations. I have been looking at commands such as polyfit, but I am not sure this is the correct route
Thanks
0 个评论
回答(1 个)
dpb
2014-7-9
For a zero-intercept model, simplest is just use the "backslash" function...
m=X\Y; % estimate slope w/ zero intercept
To plot
hold on
plot(X,m*X);
text(xpos,ypos,num2str(m,'y = %.3fx')) % write the trendline equation
xpos, ypos are coordinates to place at your desired location. A relatively low X and corresponding Y would be a good candidate w/ xpos adjusted just a little to left and the 'horizontalposition' property set to 'right'.
5 个评论
dpb
2014-7-9
编辑:dpb
2014-7-10
I don't follow...how did you "adjust" the slope to get the "adjusted" slope?
A least-squares response that looks like your coefficients of [0.096,6.462] if evaluated as least squares for a zero-intercept model the slope is going to be much, much greater 0.096 unless the range of x is very large, indeed.
For example, if I generate a set of data w/
>> x=[0:.1:5].'; % supposed range for x
>> y=polyval([0.096,6.462],x); % the data to fit
Then if I build the zero-intercept model instead I find
>> bz=x\y
bz =
2.0154
a (not surprisingly) much steeper slope to try to minimize SSE given the constraint of zero intercept.
If, otoh, I select
>> x=[1000:1005].';
>> y=polyval([0.096,6.462],x);
as the data set so missing zero by 6 isn't nearly as big a deal, then I find
>> bz=x\y
bz =
0.1024
>>
And amazingly enough, that just by pure happenstance turns out to look a lot like your result. That was purely luck, btw...
Anyways, if that doesn't answer the problem, post a small representative dataset that illustrates what you're up to.
dpb
2014-7-10
...I believe the method you just stated just causes my original equation y=0.096x+6.462 to become y=0.096x+0.
What on earth makes you think believe that? The flatlanders have a belief as well, but it's kinda' been shown to not be so. "Backslash" solves the LSQ equations for the design as given--if one does/does not include the intercept in the model, the estimation will/will not include it and certainly the result will not be the same in general. NB, however, that the dataset obviously changes how different the result is as illustrated above.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Regression 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!