How to obtain the fit line and confidence interval from fitlm

91 ビュー (過去 30 日間)
Federico
Federico 2023 年 7 月 14 日
回答済み: phenan08 2023 年 7 月 14 日
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

採用された回答

phenan08
phenan08 2023 年 7 月 14 日
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.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAnalysis of Variance and Covariance についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by