How to use fitlm to force linear fit through zero?
40 次查看(过去 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!