% Interpolating by lagrange's polynomials. function lagrange % set up interpolation points xi=[-1:1:1]; yi=f(xi); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % graph both functions to compare %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figure(1); clf; n=100; x=-1:2/n:1; y_exact=f(x); y_interp=[]; for k=1:101 y_interp=[y_interp, lagr_polyn(xi,yi,x(k))]; end plot(x,y_exact,'r-',x,y_interp,'b-'); % n-th Lagrange's interpolating polynomial % xi, yi - are the arrays of interpolating points x_i, f(x_i) % x is the point where the lagrange polynomial needs to be computed function y=lagr_polyn(xi,yi,x); % determine the size of a == number of interpolating points n=size(xi); n=n(2); % calculate the polynomial y=0; for j=1:n % Compute Lagrange's interpolating multiplier L_n,k L=1; for k=1:n if k~=j L=L*(x - xi(k))/(xi(j)-xi(k)); end end y=y+yi(j)*L; end function y=f(x) y=exp(x);