Help plotting a polynomial in MATLAB.

63 Views Asked by At

This time I want to plot he interpolation polynomial with the coefficients given by the following code:

%Code for the polynimial interpolation.
%We first define the points where we want that our polynimial passes
%through


x0=-pi/2;
y0=-1;
x1=0;
y1=0;
x2=pi/2;
y2=1;
x3=pi;
y3=0;

x=[x0,x1,x2,x3];
y=[y0,y1,y2,y3];
%Now we perform the algorithm.

c=zeros(4,1);
c(1)=y(1);
for k=2:4
    d=x(k)-x(k-1);
    u=c(k-1);
    for i=(k-2):-1:1
        u=u*(x(k)-x(i))+c(i);
        d=d*(x(k)-x(i));
    end
    c(k)=(y(k)-u)/d;


end
disp(c)

The thing is that I want to plot the results, so I have tried the following:

plot(x,y)
x1=0:4;
for i=-4:4
y1=c(1)+c(2)*(x1-x(1))+c(3)*(x1-x(1))*(x1-x(2))+c(4)*(x1-x(1))*(x1-x(2))*(x1-x(3))*(x1-x(4));
end

and

y_1 = @(x)-0.6729+4.8266*(x-x(1))-0.4855*(x-x(1))*(x-x(2))+0.0312*(x-x(1))*(x-x(2))*(x-x(3))+3.044*(x-x(1))*(x-x(2))*(x-x(3))*(x-x(4));

x_1 = 0:0.1:33.5;

plot(x_1,y_1(x_1))

But the thing is that anyone worked, so Can someone help me to plot this polynomial please?

How Can I do this without using @(x)?

Thanks a lot in advance.

1

There are 1 best solutions below

8
On

In MATLAB, when you multiply two vectors pointwise, you have to use

.*

instead of

*

For instance, you should change

y_1 = @(x)-0.6729+4.8266*(x-x(1))-0.4855*(x-x(1))*(x-x(2))+0.0312*(x-x(1))*(x-x(2))*(x-x(3))+3.044*(x-x(1))*(x-x(2))*(x-x(3))*(x-x(4));

to

 y_1 = @(x)-0.6729+4.8266*(x-x(1))-0.4855*(x-x(1)).*(x-x(2))+0.0312*(x-x(1)).*(x-x(2)).*(x-x(3))+3.044*(x-x(1)).*(x-x(2)).*(x-x(3)).*(x-x(4));

EDIT: to remove the @x, you could just have

x_1 = 0:0.1:33.5;
y_1 = -0.6729+4.8266*(x_1-x_1(1))-0.4855*(x_1-x_1(1)).*(x_1-x_1(2))+ ...
      0.0312*(x_1-x_1(1)).*(x_1-x_1(2)).*(x_1-x_1(3))+...
      3.044*(x_1-x_1(1)).*(x_1-x_1(2)).*(x_1-x_1(3)).*(x_1-x_1(4));

plot(x_1,y_1)

I put in the ...'s to write a multiline equation, since that's considered better practice.