MATLAB: Polyfit doesn’t generate the same coefficients that were inputted

polyfit

As a test I generated an array of values from a quadratic function and then used polyfit to generate coefficients for these values. Polyfit gives me different coefficients than the ones I inputted. Is there any way to fix this? I need to be able to calculate coefficients as accurately as possible from only the first half of the generated values.
My code:
x = linspace(1,100,10000); p = [.0010 0 0]; c = polyval(p,x);
poly1 = polyfit(linspace(1,5000,5000),c(1:5000),2);
f = polyval(fliplr(poly1), x);
plot(x, c);
hold on;
plot(x, f);

Best Answer

Polyfit does just fine, if you use it properly.
If you decide not to solve the same problem, then exactly why do you expect to get the same answer?
You generate c like this:
x = linspace(1,100,10000); p = [.0010 0 0]; c = polyval(p,x);
Now, lets look at the coefficients from the problem that you solved:
poly1 = polyfit(linspace(1,5000,5000),c(1:5000),2)
poly1 =
9.803e-08 1.9606e-05 0.0009803
Instead, what happens if you use the same data you generated from that polynomial?
poly1 = polyfit(x(1:5000),c(1:5000),2)
poly1 =
0.001 -7.6126e-17 5.164e-16
So poly1 is now the same as what you started with, to within some numerical crap. You can ignore the 1e-17 stuff, because it is noise down in the least significant bits.
linspace(1,5000,5000) is NOT the same set of numbers as x(1:5000). The latter set has increments of roughly 0.009901. The former, increments of 1.
Moral: If you solve two different problems, expect different answers.