As radarhead wrote in his comment, you forgot the coefficient of zero degree (p(4)
here).
Assuming x
and y
are vectors of same length n
, polyfit(x,y,n-1)
will return a vector containing the coefficients of the interpolating polynomial (of degree n
-1) in descending order.
Then, the value of the interpolating polynomial at a point z
will be given by:
p(1)*z^3 + p(2)*z^2 + p(3)*z + p(4)
Don't forget p(4)
! As Bas suggested, you can use the polyval
function to easily compute the value of a polynomial at a a given point:
polyval(p,z);
To illustrate this, see the code below, which generates 4 data points, plots those points and the polynomial interpolating them:
n = 4;
x = sort(rand(n,1));
y = rand(n,1);
p = polyfit(x,y,n-1);
figure
hold on
plot(x,y,'bo');
xx=linspace(x(1),x(end),100);
plot(xx,polyval(p,xx),'r');
hold off