fit a line in matlab

To fit a line in Matlab, you can use the polyfit function which performs a least squares polynomial fit of specified degree to the provided data. In this case, we need to specify a degree of 1 since we want to fit a line. The polyfit function returns the coefficients for a polynomial which can be used to plot the line.

Here is an example code that shows how to fit a line and plot it:

main.m
% Generate some sample data
x = 1:10;
y = 2*x + 1 + randn(size(x));

% Fit a line to the data
p = polyfit(x, y, 1);

% Evaluate the line at some points for plotting
x_fit = linspace(min(x), max(x), 100);
y_fit = polyval(p, x_fit);

% Plot the original data and the fitted line
plot(x, y, 'o')
hold on
plot(x_fit, y_fit, '-')
xlabel('x')
ylabel('y')
title('Linear Regression Example')
384 chars
19 lines

This code generates some sample data, fits a line using polyfit, evaluates the line at 100 points for plotting, and then plots both the original data and the fitted line. The resulting plot should display the line of best linear fit for the sample data set.

gistlibby LogSnag