Reputation: 109
I am looking to fit a parabola to the following data.
x = [-10:2:16];
y = [0.0334,0.0230,0.0145,0.0079,0.0033,0.0009,0.0006,0.0026,0.0067,0.0130,0.0213,0.0317,0.0440,0.0580];
[p,~,~] = polyfit(x,y,2);
x2 = linspace(-10,16,100);
y2 = polyval(p,x2);
y3 = 0.0003.*x2.^2 -0.0006.*x2 + 0.0011;
figure
plot(x,y,'o',x2,y2,x2,y3)
However, the fit does not match with the data at all. After putting the data into excel and fitting using a 2nd order polynomial there, I get a very nice fit. y = 0.0003x2 - 0.0006x + 0.0011 (excel truncating the coefficients skews the fit a bit). What is happening with polyfit with this data?
Upvotes: 1
Views: 3593
Reputation: 313
I would solve this in matlab using least squares:
x = [-10:2:16]';
Y = [0.0334,0.0230,0.0145,0.0079,0.0033,0.0009,0.0006,0.0026,0.0067,0.0130,0.0213,0.0317,0.0440,0.0580]';
plot(x,Y,'.');
A=[ones(length(x),1) x x.^2];
beta=A\Y;
hold on
plot(x, beta(1)+beta(2)*x+beta(3)*x.^2)
leg_est=sprintf('Estimated (y=%.4f+%.4fx+%.4fx^2',beta(1),beta(2),beta(3))
legend('Data',leg_est)
Upvotes: 0
Reputation: 109
Solved.
Matlab checks how many outputs the user is requesting. Since I requested three outputs even though I wasn't using them, polyfit changes the coefficients to map to a different domain xhat.
If I instead just did:
p = polyfit(x,y,2);
plot(x2,polyval(p,x2));
Then I would achieve the appropriate result. To recover the same answer using the three outputs:
[p2,S,mu] = polyfit(x,y,2);
xhat = (x2-mu(1))./mu(2)
y4 = polyval(p2,xhat)
plot(x2,y4)
Upvotes: 3