How to obtain the fit line and confidence interval from fitlm

91 visualizzazioni (ultimi 30 giorni)
Let's say I have one predictor (x) and one response (y) variable:
x=rand(100,1);
y=rand(100,1);
And I then fit a linear model (mdl) to those variables and then plot it:
mdl=fitlm(x,y,'VarNames',{'X','Y'});
plot(mdl)
The plot comes with a fit line and confidence intervals. How are those computed and how can I compute them? I've tried to use predict but the intervals are not the same
[ypred,yci]=predict(mdl,x);
hold on
plot(x,yci,'g:')
A workaround I found was to assign a handle when plotting the linear model and then get the XData and YData of the fit line and the confidence intervals, but while it does work with the fit line, it only gives me the XData and YData of the lowermost confidence interval.
How can I calculate the same fit line and confidence interval as plot(mdl)?
Thanks

Risposta accettata

phenan08
phenan08 il 14 Lug 2023
When testing your code, I get the same CI when using plot(mdl) and when using predict.
x=rand(100,1);
y=rand(100,1);
mdl=fitlm(x,y,'VarNames',{'X','Y'});
figure ;
plot(mdl) ;
[ypred,yci]=predict(mdl,x);
hold on;
plot(x,yci,"ko","DisplayName","Predicted CI")
hold off;
But you can reproduce the same type of plot by an alternative way:
figure ;
plot(x,mdl.Fitted,"r-","LineWidth",2,"DisplayName","Fit") ;
[ypred,yci_curve]=predict(mdl,x,"Prediction","curve");
[~,yci_obs]=predict(mdl,x,"Prediction","observation");
hold on ;
plot(x,yci_curve,"r.","DisplayName","Confidence bounds") ;
plot(x,yci_obs,"ro","DisplayName","Prediction bounds") ;
hold off ;
legend ;
Here, I represented both confidence and prediction intervals, which have not the same values.

Più risposte (0)

Prodotti


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by