Obtaining slope from fitlm results
85 ビュー (過去 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!