MATLAB: Polyfit fails with easy datafit

polyfit polyvar

Hello,
I have a (maybe very simple) problem with polyfit and I hope its not just a stupid misunderstanding of the polyfit function. I use polyfit inside a much more complex algorithm and I just realized, that the results from polyfit are quite bad and I wondered why so I tried a minimal example :
x = -1:0.001:+1;
y= -10*x.^2 +5 - 0.1*(x)+rand(size(x))*0.001;
[p,S,mu] = polyfit(x,y,2);
[y_polyval, delta] = polyval(p,x,S);
plot(x,y,x,y_polyval,'r');
The plot shows, that the fit is quite different from the original data. Its a very simple data set and I don't understand why polyfit returns so bad results.
Would be very grateful for a helpful advice.
EDIT: This is what I get :

Best Answer

>> x = -1:0.001:+1;
y= -10*x.^2 +5 - 0.1*(t)+rand(size(t))*0.001;
Undefined function or variable 't'.
>>
??? what's t???
Presuming it's a typo and you meant x, the problem is you used the form of polyfit that centers and scales the values but didn't use the corresponding form of polyval to scale automatically the x-vector.
If return the MU optional output from polyfit, that triggers the scaling per the doc --
[P,S,MU] = polyfit(X,Y,N) finds the coefficients of a polynomial in
XHAT = (X-MU(1))/MU(2) ...
In that case use
yhat=polyval(x,y,[],mu);
to flag polyval to scale in the evaluation (or use
yhat=polyval((x-mu(1))/mu(2),y);
to do the scaling manually)
ADDENDUM
[P,S,MU] = polyfit(X,Y,N) finds the coefficients of a polynomial in
XHAT = (X-MU(1))/MU(2) ...
@TMW -- I think this is a poorly designed interface to the two functions to have the output variable's existence be the flag that the scaling is occurring; imo it should be an optional input flag from user requesting it instead. While there may be other functions with similar behavior in Matlab or one of the Toolboxes this is the only case I can think of of all of the Matlab functions I use regularly that has the behavior. Thus, it's an aberration and unexpected and leads to errors.
Yes, OP could have found it with careful perusing of the documentation, but even I had to puzzle for a minute until I recalled the anomaly despite 20+ yr w/ Matlab behavior and "knowing" of this peculiarity.
Related Question