Linear Regression Plot in MATLAB: polyfit, lsline & fitlm Guide

MATLAB Illustration

Notes on Plotting Linear Regression in MATLAB

Linear regression finds the best-fitting straight line through data points using the least-squares method. MATLAB provides simple built-in functions to compute and plot it.

Key Methods

  1. polyfit() + polyval() – Most common for simple linear (degree 1).
  2. lsline() – Quick overlay on scatter plot.
  3. fitlm() – For detailed statistics (from Statistics Toolbox).

Basic Steps (polyfit Method)

% Sample data x = [1 2 3 4 5 6 7 8 9 10]; y = [2.3 4.1 5.8 7.2 9.0 10.5 12.1 13.8 15.2 16.9]; % Roughly linear with noise % Compute linear fit (slope m, intercept c) p = polyfit(x, y, 1); % Returns [m c] % Generate fitted line x_fit = linspace(min(x), max(x), 100); y_fit = polyval(p, x_fit); % Plot figure; scatter(x, y, 'filled', 'b'); hold on; plot(x_fit, y_fit, 'r-', 'LineWidth', 2); grid on; xlabel('X'); ylabel('Y'); title(['Linear Regression: y = ' num2str(p(1),3) 'x + ' num2str(p(2),3)]); legend('Data Points', 'Best Fit Line'); hold off;
 

Quick Method with lsline

scatter(x, y, 'filled'); lsline; % Adds least-squares line automatically title('Scatter with Linear Regression Line');
 
 

Advanced: fitlm for Statistics

mdl = fitlm(x, y); % Creates linear model plot(mdl); % Plots data, fit, and confidence bounds disp(mdl); % Shows R-squared, p-values, coefficients
 
 

Tips

  • Use polyfit(x,y,1) for slope and intercept.
  • Confidence intervals: Use polyfit with output [p,S] and polyconf.
  • Multiple regression: polyfit for higher degrees or fitlm for multi-variable.

Ideal for data analysis, trend lines, and curve fitting.

What Our Students Say

★★★★★

“I got full marks on my MATLAB assignment! The solution was perfect and delivered well before the deadline. Highly recommended!”

Aditi Sharma, Mumbai
★★★★☆

“Quick delivery and excellent communication. The team really understood the problem and provided a great solution. Will use again.”

John M., Australia

Latest Blogs

Explore how MATLAB Solutions has helped clients achieve their academic and research goals through practical, tailored assistance.

MATLAB Autonomous Vehicle Path Planning Project for Students: Step-by-Step with Code

One of the most fascinating and sought-after projects for engineering students is autonomous vehicles. One of the main challenges in the development of self-driving cars is path planning, which is the process of determining a safe, collision-free route from start to o

Battery Management System (BMS) in Electric Vehicles Using MATLAB & Simulink: A Comprehensive Guide

The Battery Management System (BMS) serves as the intelligent brain of an electric vehicle (EV) battery pack. It ensures safety, maximizes performance, extends battery life, and optimizes energy usage in real-world driving conditions. As EVs become mainst