%function out=LaGrange(xdata,ydata,x) % % Input: % xdata: points x0...xn % ydata: function values f(x0)...f(xn) % these should be row vectors % x: point at which to interpolate the polynomial % Output: % out: This is P(x), where P is the unique nth-order % polynomial with P(xi)=f(xi) %sample code to test: %LaGrange([1 2 3],[4 5 6],12) %answer should be 15 function out=LaGrange(xdata,ydata,x) n=size(xdata,2)-1; out=0; for i=0:n out=out+LP(i,xdata,x)*ydata(i+1); %this implements lagrange interpolation: P(x)=sum_i(L_i(x)*f(x_i)) end end %function out=LP(i,xdata,x) % % Input: % i: index number of the LaGrange polynomial to compute % xdata: coordinate of the points x0...xn % x: point at which to compute L_i % Output: % out: value of L_i(x) function out=LP(i,xdata,x) n=size(xdata,2)-1; out=1; for j=0:n if not(eq(i,j)) out=out*(x-xdata(j+1))/(xdata(i+1)-xdata(j+1)); %this is the correct product for the ith lagrange polynomial end end end