How to obtain the fit line and confidence interval from fitlm
92 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Analysis of Variance and Covariance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!