MATLAB: Polyfit doesn’t fit the data

polyfit

>> mdl=fitlm(X,Y)
mdl =
Linear regression model:
y ~ 1 + x1
Estimated Coefficients:
Estimate SE tStat pValue
________ _______ _______ __________
(Intercept) 16.325 1.8303 8.9194 1.054e-16
x1 -1.1809 0.14751 -8.0059 4.5928e-14
Number of observations: 250, Error degrees of freedom: 248
Root Mean Squared Error: 1.19
R-squared: 0.205, Adjusted R-Squared 0.202
F-statistic vs. constant model: 64.1, p-value = 4.59e-14
>> plot(X,Y,'.')
hold on
plot(X,polyval(p,X),'r.')
hold on
f=16.3250-1.1809*X
plot(X,f,'.b')
Attached figure:
in blue: data
in red: polyfit regression
in green: fitlm model
polyfit does not fit the data whereas fitlm does. Is there anything I can do to fix that? I would rather not use fitlm as I have to do thousand of regressions and it seems more complex and using more memory

Best Answer

Hi,
I guess it's another problem here: note, that if you call polyfit with
[p,s,mu] = polyfit ...
you get the scaled and shifted representation of the polynomial. Therefore you would need to take mu to transform logX->\hat logX (see doc of polyfit).
If you call polyfit only with output p you get a different result that coincides with fitlm.
Titus