Plotting Linear Regression and Best Fit Lines in MATLAB

MATLAB Illustration

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()

MATLAB
% 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 Turnitin plagiarism reports.

Verified Feedback

What Engineering Students Say

Real feedback from students across top engineering universities worldwide.

Verified Student

“I got full marks on my MATLAB DSP assignment! The filter design code was completely vectorized, the frequency response plots were exact, and the delivery was 8 hours before my deadline. Highly recommended!”

AS

Aditi Sharma

IIT Bombay • Signal Processing Coursework
Verified Student

“Our Simulink EV powertrain model had severe algebraic loop and solver errors. The MATLABSolutions team fixed the solver configuration in 4 hours and provided an annotated scope diagram. Lifesaver for my final year!”

JM

John M.

Monash University, Australia • Simulink Dynamic Model
Technical Knowledge Base

Latest MATLAB Guides & Tutorials

Explore deep-dive technical articles written by our engineering team to master complex MATLAB & Simulink topics.

MATLAB Guide 5 Min Read

Why Coulomb Counting Fails: Implementing an Extended Kalman Filter (EKF) for EV Battery SoC in MATLAB/Simulink

If you have ever bench-tested a battery pack or evaluated an electric vehicle prototype, you have probably run into this problem: the dashboard displays 45% State of Charge (SoC...

MATLAB Guide 5 Min Read

Simulink in the Age of AI: Why ChatGPT Fails at Engineering Simulations (And What Professors Expect in 2026)

1. The 2026 Classroom Reality: Why Professors Are Cracking Down Walk into an engineering computer lab at Georgia Tech, Purdue, or MIT this semester, and you will notic...