How to use fitlm to force linear fit through zero?
36 ビュー (過去 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!