Why is there an error on my plot line?

I am writing a code that plots Lagrange-Polynomial-Interpolation and the part that's messing up is the plot(X,P,'b');
I have inserted a % to make it a comment and test the rest of the code and the rest of the code works. But when I remove the % from the plot(X,P,'b'); line, an error pops up at this line. What am I doing wrong?
Here's the entire code:
f = @(x) 3*exp(-x)+2*sin(x);
X = 0:3;
Y = f(X);
n = length(X);
P = 0;
syms x;
L = sym(zeros(size(X)));
for i = 1:n
L(i) = 1;
for j = 1:n
if (j ~= i)
L(i) = L(i)*(x-X(j))/(X(i)-X(j));
end
end
P = P + Y(i)*L(i);
end
disp(P)
plot(X,P,'b');
hold on;
grid on;
fplot(f,[0,3],'r');
hold on;
plot(X,Y,'or');

 Réponse acceptée

f = @(x) 3*exp(-x)+2*sin(x);
X = 0:3;
Y = f(X);
n = length(X);
P = 0;
syms x;
L = sym(zeros(size(X)));
for i = 1:n
L(i) = 1;
for j = 1:n
if (j ~= i)
L(i) = L(i)*(x-X(j))/(X(i)-X(j));
end
end
P = P + Y(i)*L(i);
end
disp(P)
P = double(subs(P,X));
plot(X,P,'b');
hold on;
grid on;
fplot(f,[0,3],'r');
hold on;
plot(X,Y,'or');

1 commentaire

Paul  Jones
Paul Jones le 8 Fév 2022
It worked! what is the reason to use double(subs as opposed to what I was doing?

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by