least squares polynomial in matlab

To perform least squares polynomial regression (or curve fitting) in MATLAB, you can use the polyfit function. This function takes in the x and y data points, as well as the degree of the polynomial you want to fit. It returns the coefficients of the polynomial that best fits the data.

Here's an example:

main.m
% Sample data
x = [1 2 3 4 5];
y = [5 7 9 11 13];

% Degree of polynomial to fit
n = 2;

% Perform least squares polynomial regression
p = polyfit(x,y,n);

% Evaluate the polynomial at some points
x_eval = linspace(1,5,100);
y_eval = polyval(p,x_eval);

% Plot the data and the fitted polynomial
plot(x,y,'o',x_eval,y_eval);
325 chars
17 lines

In this example, we have data points (1,5), (2,7), (3,9), (4,11), and (5,13). We want to fit a second-degree polynomial (a parabola) to this data. We use the polyfit function to obtain the coefficients of the parabola that best fits the data. We then evaluate the parabola at 100 equally spaced points between 1 and 5, and plot both the data and the fitted parabola.

gistlibby LogSnag