Obtaining slope from fitlm results
109 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
With results from fitlm, how does one disentangle the linear regression's slope? I'm simply trying to plot the regression over the data. (I expect this'll be an easy answer; thank you in advance.)
0 commentaires
Réponse acceptée
dpb
le 2 Juil 2017
Modifié(e) : dpb
le 2 Juil 2017
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 commentaires
dpb
le 4 Juil 2017
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."
Plus de réponses (1)
Image Analyst
le 3 Juil 2017
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 commentaires
Catherine Mauck
le 16 Fév 2020
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
le 16 Fév 2020
"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.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!