MATLAB: Polynomial doesnt fit with original data

curve fitting

Hi, I give Matlab 2009a vectors X and Y. I plot(X,Y) and I want to fit a polynomial on it. on the plot, I can see a good fit with 6th order polynomial. Then I save the coefficients of polynomial (say vector A) and again plot(polyval(A,X). But they dont match with the original curve. They are not even close!
these are X and Y:
1000 0.003719
1100 0.004066
1200 0.004507
1300 0.005044
1400 0.005683
1500 0.006432
1600 0.0073
1700 0.0083
1800 0.009449
1900 0.01077
2000 0.01227
2100 0.014
2200 0.01597
2300 0.01824
2400 0.02087
2500 0.02391
2600 0.02749
2700 0.03175
2800 0.03693
2900 0.04343
3000 0.05208
3100 0.06516
3129.9 0.07103
and I got A from basic fitting tools as below:
Coefficients:
p1 = 0.00097657
p2 = 0.001743
p3 = -0.00084778
p4 = -0.00046857
p5 = 0.0064581
p6 = 0.01318
p7 = 0.013886
Norm of residuals =
0.0011309
I must mention that when I was fitting I got this warning: "polynomial is badly conditioned" but the fit looks good.
what am I doing wrong. I could see this problem in Excel too.
  • I need to have a function (Y=f(X)) for my data. If I shouldn't use polynomial fitting, do you have other suggestions?

Best Answer

I don't know what you did, but when I did it, it looks great:
xy = [1000 0.003719
1100 0.004066
1200 0.004507
1300 0.005044
1400 0.005683
1500 0.006432
1600 0.0073
1700 0.0083
1800 0.009449
1900 0.01077
2000 0.01227
2100 0.014
2200 0.01597
2300 0.01824
2400 0.02087
2500 0.02391
2600 0.02749
2700 0.03175
2800 0.03693
2900 0.04343
3000 0.05208
3100 0.06516
3129.9 0.07103]
% Extract x and y.
x = xy(:, 1);
y = xy(:, 2);
% Get the fit coefficients.
[coeffs, S, mu] = polyfit(x, y, 6);
% Get the fitted values.
fittedY = polyval(coeffs, x, S, mu);
% Plot everything.
plot(x, y, 'r*', 'LineWidth', 2);
hold on;
plot(x, fittedY, 'bd-', 'LineWidth', 2, 'MarkerSize', 15);
grid on;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);