How to use fitlm to force linear fit through zero?
조회 수: 41 (최근 30일)
이전 댓글 표시
I want to use the fitlm function to fit a linear model that goes through zero, i.e. only the linear term and no offset. I'm confused by the explanation of how to specify the terms that the model must include. Is this right?
% Create example data
x = 1:100;
y = x*rand(1) + rand(size(x))*10 + rand(1)/10;
% x1 means fit linear term (i.e. slope), and -1 means do NOT include offset (e.g. intercept), right?
fittedLinearModel = fitlm(x, y, 'y ~ x1 - 1');
댓글 수: 0
채택된 답변
Matthew Blomquist
2023년 10월 17일
That looks correct to me. I double checked by plotting the x and y values, and then the best fit line, and it goes through 0. Then I ran the code again but added 30 to y before fitting so that the unconstrained best fit would not go through 0, but it appears the fit does, in fact, go through 0 still.
% Create example data
x = 1:100;
y = x*rand(1) + rand(size(x))*10 + rand(1)/10 + 30 ;
% x1 means fit linear term (i.e. slope), and -1 means do NOT include offset (e.g. intercept), right?
fittedLinearModel = fitlm(x, y, 'y ~ x1 - 1');
figure() ;
scatter( x , y ) ;
hold on ;
plot( x , fittedLinearModel.Coefficients.Estimate*x )
So, based on that evidence, I believe you are correct!
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!