Obtaining slope from fitlm results
109 次查看(过去 30 天)
显示 更早的评论
采纳的回答
dpb
2017-7-2
编辑:dpb
2017-7-2
Oh, it's a tangled web TMW has weaved, fer shure...what with all the different mechanisms to do the same thing in different toolboxen plus the base product, and nary the doubled twain shall meet...
Anyhoo, fitlm in Statistics Toolbox returns an object of the Linear Model class. There's a page documenting properties and methods for it you can get to by clicking on the Output Arguments section link mdl or the 'See Also' section for more details.
In short, the coefficients are obtainable by referencing the field Estimate in the table returned by Coefficients property. So, given
lm=fitlm(x,y,'poly1'); % a linear model
betahat=lm.Coefficients.Estimate; % the coefficients
NB: These are case-sensitive names, btw...and must be spelled-out in their entirety, none of this "first n characters stuff" here (not that that's any different than for other dot addressing, just noting it).
BTW, the order of these are intercept first which is in direct conflict with the venerable polyfit/polyval pair.
To just evaluate the fit to draw the regression line, use predict method that will get the coefficients for you given just the model object and x vector.
5 个评论
dpb
2017-7-4
Hmmm...I thought I said that a couple of times... :)
"BTW, the order of these are intercept first which is in direct conflict with the venerable polyfit/polyval pair."
更多回答(1 个)
Image Analyst
2017-7-3
Like dpb, I was also wondering why you don't simply use polyfit() if you just want to fit a simply line. The first coefficient is the slope:
coefficients = polyfit(x, y, 1);
slope = coefficients(1);
If your linear model not a simple y=mx+b line? If not, what is your model and supply us your data.
4 个评论
Catherine Mauck
2020-2-16
My understanding is also that polyfit does not allow you to specify an intercept of 0 (or at least from my brief Googling trying to solve that, that led me to fitlm).
dpb
2020-2-16
"My understanding is also that polyfit does not allow you to specify an intercept of 0..."
True; polyfit/polyval are a very simplistic toolset that was introduced in the very earliest years of MATLAB. It's useful for the simple case if all one cares about is the plain-vanilla results. Anything more than that is more easily obtained or can only be obtained by one or more of the later tools/functions or by reverting to base definitions and backslash for solution and then computing any desired statistics from first principles.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!