fonction d'interpolation avec la méthode de newton in matlab

To implement the Newton's method of interpolation in MATLAB, we can use the interp1 function which uses the Newton's divided difference formula under the hood. Here's an example code:

main.m
% Sample data
x = [1 2 3 4];
y = [3 1 4 2];

% Compute divided difference coefficients
dd = divdiff(x, y);

% Define a function to evaluate the polynomial using divided differences
f = @(x) newton_eval(x, x, dd);

% Compute interpolated values for some new x values
x_new = linspace(0, 5, 101);
y_new = f(x_new);

% Plot original data and interpolated values
plot(x, y, 'o', x_new, y_new);
legend('Data', 'Interpolated');
xlabel('X');
ylabel('Y');

function c = divdiff(x, y)
% Compute divided difference coefficients
    n = length(x);
    c = y;

    for j = 2:n
        for i = n:-1:j
            c(i) = (c(i) - c(i-1)) / (x(i) - x(i-j+1));
        end
    end
end

function y = newton_eval(x, xk, c)
% Evaluate interpolating polynomial using divided differences
    n = length(xk);
    y = c(n);

    for i = n-1:-1:1
        y = c(i) + (x - xk(i)) .* y;
    end
end
871 chars
42 lines

The divdiff function computes and returns the divided difference coefficients c given the input x and y vectors. The newton_eval function evaluates the interpolating polynomial using the divided differences and returns the interpolated values of y for the given x values.

We then use these functions to compute the divided difference coefficients for the given x and y vectors, define a function f to evaluate the interpolated values using the Newton's method, and then use f to compute the interpolated values for some new x_new values. Finally, we plot the original data and the interpolated values using the plot function.

gistlibby LogSnag