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;enddisp(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')
MATLAB: How to properly plot Lagrange Interpolation
interpolationlagrangeMATLAB
Best Answer