quadratic lagrange interpolation in matlab

To perform quadratic Lagrange interpolation in MATLAB, first define the function to be interpolated and the interpolation points.

Then, create a function that computes the Lagrange basis polynomials and weights for each interpolation point. Finally, use these basis polynomials and weights to compute the interpolated function values at desired points.

Here is a sample code that performs quadratic Lagrange interpolation using MATLAB:

main.m
% Define function to be interpolated
f = @(x) sin(x);

% Define interpolation points
x_interp = [-1, 0, 1];

% Compute Lagrange basis polynomials and weights
l0 = @(x) (x-x_interp(2))*(x-x_interp(3))/((x_interp(1)-x_interp(2))*(x_interp(1)-x_interp(3)));
l1 = @(x) (x-x_interp(1))*(x-x_interp(3))/((x_interp(2)-x_interp(1))*(x_interp(2)-x_interp(3)));
l2 = @(x) (x-x_interp(1))*(x-x_interp(2))/((x_interp(3)-x_interp(1))*(x_interp(3)-x_interp(2)));
w0 = f(x_interp(1))/(l0(x_interp(1))*(x_interp(1)-x_interp(2))*(x_interp(1)-x_interp(3)));
w1 = f(x_interp(2))/(l1(x_interp(2))*(x_interp(2)-x_interp(1))*(x_interp(2)-x_interp(3)));
w2 = f(x_interp(3))/(l2(x_interp(3))*(x_interp(3)-x_interp(1))*(x_interp(3)-x_interp(2)));

% Define points at which to interpolate
x_vals = linspace(-2,2,101);

% Compute interpolated function values
y_vals = w0*l0(x_vals) + w1*l1(x_vals) + w2*l2(x_vals);

% Plot original function and interpolated function
plot(x_vals, f(x_vals));
hold on;
plot(x_vals, y_vals);
legend('Original function', 'Interpolated function');
1050 chars
26 lines

gistlibby LogSnag