plot a line of best fit in matlab

To plot a line of best fit in MATLAB, you can use the polyfit function to fit a polynomial of degree 1 (a straight line) to your data points. Then, you can use the polyval function to evaluate the polynomial over a range of x-values and plot it on the graph.

Here's an example:

main.m
% Example data
x = [1, 2, 3, 4, 5];
y = [2, 4, 6, 8, 10];

% Fit a polynomial of degree 1
coefficients = polyfit(x, y, 1);

% Generate x-values for plotting
x_values = linspace(min(x), max(x), 100);

% Evaluate the polynomial for the corresponding y-values
y_values = polyval(coefficients, x_values);

% Plot the original data points
scatter(x, y, 'bo', 'filled');
hold on;

% Plot the line of best fit
plot(x_values, y_values, 'r');

% Add labels and title
xlabel('x');
ylabel('y');
title('Line of Best Fit');

% Show the grid and legend
grid on;
legend('Data points', 'Line of Best Fit');
591 chars
29 lines

This code will create a scatter plot of the original data points and plot a red line representing the line of best fit. The polyfit function calculates the coefficients for the line of best fit, and the polyval function evaluates the line for the x-values generated by linspace.

Make sure to adjust the values of x and y with your own data before running the code.

related categories

gistlibby LogSnag