least squares polynomial of degree 2 in matlab

To find the least-squares polynomial of degree 2 in MATLAB, you can use the polyfit function.

Here's an example:

main.m
% Example data
x = [1, 2, 3, 4, 5]';
y = [2.3, 3.5, 4.1, 5.0, 6.1]';

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

% Evaluate the polynomial at some points
x_eval = linspace(0, 6, 100)';
y_eval = polyval(p, x_eval);

% Plot the data and the fitted polynomial
plot(x, y, 'o');
hold on;
plot(x_eval, y_eval);
xlabel('x');
ylabel('y');
legend('Data', 'Fit');
385 chars
19 lines

This code fits a polynomial of degree 2 to the x and y data using polyfit, evaluates the fitted polynomial at 100 points between 0 and 6 using polyval, and then creates a plot of the data with the fitted polynomial superimposed.

gistlibby LogSnag