least squares polynomial of degree n in matlab

To obtain the least-squares polynomial of degree n in Matlab, you can use the polyfit function. Here's an example:

main.m
% Define x and y vectors
x = [-2, -1, 0, 1, 2];
y = [3, -1, -2, 1, 4];

% Fit a polynomial of degree n=2 using least squares
n = 2;
p = polyfit(x, y, n);

% Plot the data and the fitted polynomial
plot(x, y, 'o', x, polyval(p, x), '-')
legend('Data', 'Fitted polynomial')
272 chars
12 lines

In this example, we define the x and y vectors that represent our data points. We then use the polyfit function to fit a polynomial of degree 2 to the data using least squares. The resulting coefficients of the polynomial are stored in the p variable. Finally, we plot both the original data points and the fitted polynomial using the plot and polyval functions.

gistlibby LogSnag