interpolation polynimial in matlab

In MATLAB, we can use the polyfit and polyval functions to interpolate a polynomial.

First, suppose we have n data points, represented by vectors x and y. We want to fit an m-degree polynomial to these points, where m < n.

To do this, we can use the polyfit function. Here's an example usage:

main.m
% Input data
x = [0 1 2 3 4 5];
y = [1 0.8 0.6 0.3 0.1 0.05];

% Fit a polynomial of degree 3 to the data
coefficients = polyfit(x, y, 3);
139 chars
7 lines

This will return a row vector of length m+1, where the coefficients are ordered from highest to lowest degree. So in this case, coefficients will be a 1x4 vector, with the coefficients for the cubic polynomial.

Now, to evaluate the polynomial at a specific value, let's say xi, we can use the polyval function. Here's an example:

main.m
% Evaluate the cubic polynomial at x = 2.5
xi = 2.5;
yi = polyval(coefficients, xi);
85 chars
4 lines

This will return the value of the polynomial at x=2.5.

Alternatively, if we want to evaluate the polynomial at multiple points, we can pass in a vector of x values to the polyval function:

main.m
% Evaluate the cubic polynomial at several x values
xi = [1 2 3 4 5];
yi = polyval(coefficients, xi);
102 chars
4 lines

This will return a vector yi containing the values of the polynomial evaluated at each xi.

gistlibby LogSnag