% Example: LagrangeInterp % Find the second-degree Lagrange interpolation polynomial for the % specified x and y arrays. Then, use this polynomial to find the % interpolated value at x=0.3. % specify x array x = [0.1 0.5 0.9]; % specify y array y = [0.12 0.47 0.65]; % call the LagrangeInterp function with x=0.3 yi = LagrangeInterp(x, y, 0.3); % display the interpolated value disp(yi); function yi = LagrangeInterp(x, y, xi) % % LagrangeInterp finds the Lagrange interpolating % polynomial that fits the data (x,y) and uses it % to find the interpolated value at xi. % % yi = LagrangeInterp(x, y, xi) where % % x, y are n-dimensional row or column vectors of data, % xi is a specified point, % % yi is the interpolated value at xi. % % find the number of elements in x n = length(x); % pre-allocate L with all zeros L = zeros(1, n); % loop to calculate the Lagrange coefficients of the polynomial for i=1:n, L(i) = 1; for j=1:n, if j ~= i, L(i) = L(i) * (xi - x(j)) / (x(i) - x(j)); end end end % add the polynomial terms together yi = sum(y .* L); end