필터 지우기
필터 지우기

How to obtain the fit line and confidence interval from fitlm

조회 수: 75 (최근 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 CenterFile Exchange에서 Linear and Nonlinear Regression에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by