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

3 views (last 30 days)
Yingjin Liu on 25 Sep 2022
Edited: dpb on 26 Sep 2022
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
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!

dpb on 25 Sep 2022
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 CommentsShowHide 1 older comment
dpb on 26 Sep 2022
Edited: dpb on 26 Sep 2022
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.

### Categories

Find more on Multiple Linear Regression in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!