How do I properly plot Lagrange Interpolation ?

x=[-2 1 3 5 ];
y=[0 -1.8 -1.2 -1.6];
sum=0;
for i=1:length(x)
p=1;
for j=1:length(x)
if j~=i
c = poly(x(j))/(x(i)-x(j));
p = conv(p,c);
end
end
term = p*y(i);
sum= sum + term;
end
disp(sum);
xx = linspace(min(sum), max(sum), 100); % Bunch of new samples for a smoother plot
yy = sum(1)*xx.^3 + sum(2)*xx.^2 + sum(3)*xx + sum(4);
plot(x, y, '-s')
hold on
plot(xx,yy,'-r')
%plot(sum,'-o')
xlabel('x'), ylabel('y'), title('Lagrange Polynomial Fit ')
legend('Data Collection', 'Lagrange Polynomial Fit', 'Location', 'northeast')

1 Kommentar

Yo mama
Yo mama am 20 Mär. 2020
I know that y(2) is -1.5 and where I went wrong was in xx and yy i just dont really know how to do it at all lol

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Sriram Tadavarty
Sriram Tadavarty am 20 Mär. 2020

1 Stimme

Hi Daniel,
Update the variable xx with the limits of x rather than sum, and you would see a clear plot. Something like this
xx = linspace(-2, 5, 1000); % Bunch of new samples for a smoother plot
% -2 and 5 are minimum and maximum values of x
Hope this helps.
Regards,
Sriram

3 Kommentare

Yo mama
Yo mama am 20 Mär. 2020
does this now affect my "yy"? I did this change and now my plots dont work
Sriram Tadavarty
Sriram Tadavarty am 20 Mär. 2020
Bearbeitet: Sriram Tadavarty am 20 Mär. 2020
May i know what are you referring here about plots not working, xx has just increased it's span.
It would give a plot as attached.
Yo mama
Yo mama am 20 Mär. 2020
Never mind I just needed to open it in a new window, thank you sriram

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Interpolation finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 20 Mär. 2020

Kommentiert:

am 20 Mär. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by