MATLAB: Fit equation not correct for x vector

curve fittingCurve Fitting Toolboxequation

Hi everyone,
I am trying to fit a serie (x,y) of data with a polynomial equation. I have found the equation that fit my data and well reproduce the trend. Nevertheless, the equation solution for the x vector does not give the initial y values. I post the code to be clearer.
Thank you in advance for your help!
x2= [8;8.5;9;9.3;9.5;9.8]; y2=[0.280;0.283;0.287;0.293;0.309;0.350]; curvefit = fit(x2,y2,'poly4','normalize','off'); figure,plot(curvefit,x2,y2) %the fitting weel reproduce data
% equation given by the fitting p1 = 0.005065 ; p2 = 0.0148 ; p3 = 0.01398 ; p4 = 0.008919 ; p5 = 0.2871 ; y2f=p1*x2.^4 + p2*x2.^3 + p3*x2.^2 + p4*x2 + p5; figure,scatter(x2,y2) hold on,plot(x2,y2f) %the y values given by the fitting equation are far from the initial y values

Best Answer

NEVER use short digit approximations to double precision numbers.
x2= [8;8.5;9;9.3;9.5;9.8];
y2=[0.280;0.283;0.287;0.293;0.309;0.350];
curvefit = fit(x2,y2,'poly4','normalize','off');
curvefit
curvefit =
Linear model Poly4:
curvefit(x) = p1*x^4 + p2*x^3 + p3*x^2 + p4*x + p5
Coefficients (with 95% confidence bounds):
p1 = 0.02196 (-0.1672, 0.2111)
p2 = -0.7435 (-7.493, 6.006)
p3 = 9.434 (-80.72, 99.59)
p4 = -53.16 (-587.4, 481.1)
p5 = 112.5 (-1073, 1298)
So I don't know where you got those coefficients from, but they don't even correspond to the fit! This is the biggest reason for your problem.
The data that you gave us has a completely different set of fitted coefficients. But even there, DON'T ever use short approximations to those coefficients!!!!!!!!!!!!!!
Better approximations are:
coeffvalues(curvefit)
ans =
0.0219598636195908 -0.743494138038658 9.4337274043818 -53.1599385897607 112.522326044507
But even they are not exact.
Don't forget that if x is on the order of 10, then when you raise x to the 4th power, x^4 is on the order of 10000. So an error of 1 part in 10000 in the coefficient of x^4 may well produce an error on the order of +/- 1 in p(1)*x^4.
Is that significant? It sure as hell is! The data itself has y on the order of 0.3. If you add some random component that is +/- 1 to 0.3, what do you expect? Complete garbage.
(Actually, it won't be quite that large an error, since p(1) was~0.02, but the trash so created by use of poor approximations to the coefficients will be significant. Had the model been a slightly higher order, you would have gotten complete garbage out.)