How to use fitlm to force linear fit through zero?

36 views (last 30 days)
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');

Accepted Answer

Matthew Blomquist
Matthew Blomquist on 17 Oct 2023
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!

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!