Why my results of regress function and fitlm function are different?

조회 수: 9 (최근 30일)
Yingjin Liu
Yingjin Liu 2022년 9월 25일
편집: dpb 2022년 9월 26일
My code is:
clear all
clc
x=[1 2 3 4 5 6 7 8 9 10];
y=[4 5 2 7 2 8 10 2 1 5];
tbl = table(y' , x');
mdl = fitlm(tbl,'linear')
b = regress(y',[ones(size(x',1),1),x'])
I have added an intercept when operating regress function. But the results are still different.
Here are the results:
fitlm function:
mdl =
Linear regression model:
Var2 ~ 1 + Var1
Estimated Coefficients:
Estimate SE tStat pValue
_________ _______ _________ ________
(Intercept) 5.6144 1.9347 2.902 0.019832
Var1 -0.024876 0.35803 -0.069479 0.94631
Number of observations: 10, Error degrees of freedom: 8
Root Mean Squared Error: 3.21
R-squared: 0.000603, Adjusted R-Squared: -0.124
F-statistic vs. constant model: 0.00483, p-value = 0.946
regress function
b =
4.7333
-0.0242
I'm wondering the reason of the difference. And I want to know when should I use fitlm or regress. Thanks!

답변 (1개)

dpb
dpb 2022년 9월 25일
I don't see that...I'm guessing a different y vector, somehow, maybe???
x=[1 2 3 4 5 6 7 8 9 10].';
y=[4 5 2 7 2 8 10 2 1 5].';
mdl=fitlm(x,y,'linear');
fliplr(mdl.Coefficients.Estimate.')
ans = 1×2
-0.0242 4.7333
fliplr(regress(y,[ones(size(x)) x]).')
ans = 1×2
-0.0242 4.7333
polyfit(x,y,1)
ans = 1×2
-0.0242 4.7333
  댓글 수: 2
Yingjin Liu
Yingjin Liu 2022년 9월 26일
Thank you!
I checked your code and mine, then I found I set y' in the first column. Therefore, the result of fitlm was the regression of x~1+y. Now I see. When using regress command, it is regress(y,x). While using fitlm, it is fitlm(x,y).
dpb
dpb 2022년 9월 26일
편집: dpb 2022년 9월 26일
I whiffed on the reversal when the variables were buried in the table reference for your model, sorry.
"...it is regress(y,x). While using fitlm, it is fitlm(x,y)."
Yes, this is another case where TMW created an unnecessary user confusion/chance for error such as here by having the oddball regression routine that doesn't match any of the others in the stable. It's just poor user interface design despite the theoretical statement that one "regresses y on x"; writing the input arguments in that order simply is completely inconsistent with all regression routines and so is user error bound to trap the unwary.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Model Building and Assessment에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by