Pergunta

I've some x.mat and y.mat.

And I would like to find the polynomial equation from this.

I've tried

p = polyfit(x,y,3);

with y2 = p(1)*x.^3 + p(2)*x.^2 + p(3)*x

but my y2 is not equal to the original y . What is wrong ? Thanks you

Foi útil?

Solução

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

enter image description here

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top