Plotting Linear Regression and Best Fit Lines in MATLAB
Vectorized implementations, execution benchmarks, and step-by-step programming documentation.
Linear regression in MATLAB models the relationship between dependent and independent variables by fitting a linear equation to observed data points.
Fitting and Plotting a Line of Best Fit with polyfit()
% Sample data points x = [1 2 3 4 5 6 7 8 9 10];
y = [2.1 3.9 6.2 8.1 10.2 11.9 14.1 16.0 17.8 20.1];
% Fit 1st-degree polynomial (linear fit) p = polyfit(x, y, 1);
% p(1) = slope, p(2) = intercept
% Evaluate fit over fine grid x_fit = linspace(min(x), max(x), 100);
y_fit = polyval(p, x_fit);
% Plot data points and linear regression line
figure;
scatter(x, y, 'filled', 'b');
hold on;
plot(x_fit, y_fit, 'r-', 'LineWidth', 2);
grid on;
xlabel('Independent Variable X');
ylabel('Dependent Variable Y');
title('Linear Regression Plot in MATLAB');
legend('Observed Data', 'Best Fit Line');Need Expert Guidance with MATLAB or Simulink?
Our 500+ PhD engineers provide verified MATLAB code, custom Simulink models, and 1-on-1 tutoring with comprehensive code quality verification.