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');

 Accepted Answer

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 Comment

It worked! what is the reason to use double(subs as opposed to what I was doing?

Sign in to comment.

More Answers (0)

Asked:

on 8 Feb 2022

Commented:

on 8 Feb 2022

Community Treasure Hunt

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

Start Hunting!