Linear Regression in Matlab Programming

MATLAB Illustration

Linear regression models the relationship between a dependent target variable (y) and an independent predictor variable (x) using a straight-line equation (y = mx + c). In MATLAB, you can perform linear regression using polynomial fitting, matrix algebra, or high-level statistical modeling objects.

Step 1: Define Dataset Vectors

Define predictor variable vector x and response variable vector y:

MATLAB
x = [1 2 3 4 5 6];
y = [2.2 2.8 3.6 4.5 5.1 5.9];

Step 2: Calculate Regression Coefficients

Method 1: Using polyfit()

MATLAB
% Fit 1st-degree (linear) polynomial coeff = polyfit(x, y, 1);
slope = coeff(1);
intercept = coeff(2);
fprintf('Slope (m): %.4f, Intercept (c): %.4f ', slope, intercept);

Method 2: Using Matrix Least Squares Algebra

MATLAB
% Construct design matrix with intercept column X = [x(:) ones(length(x), 1)];
Y = y(:);
% Solve normal equations: theta = (X^T * X)^(-1) * X^T * Y theta = (X' * X)  (X' * Y);
slope = theta(1);
intercept = theta(2);
fprintf('Slope (m): %.4f, Intercept (c): %.4f ', slope, intercept);

Method 3: Using fitlm() for Complete Statistical Output

MATLAB
% Fit LinearModel object mdl = fitlm(x, y);
disp(mdl);

Step 3: Predicting Values and Plotting Regression Line

Compute fitted values y_fit and plot the linear regression fit against raw data:

MATLAB
y_fit = slope * x + intercept;
figure;
scatter(x, y, 'filled', 'MarkerFaceColor', 'b');
hold on;
plot(x, y_fit, 'r-', 'LineWidth', 2);
title('Linear Regression Model Fit');
xlabel('Independent Variable (x)');
ylabel('Dependent Variable (y)');
legend('Observed Data', 'Fitted Line', 'Location', 'northwest');
grid on;
hold off;

Step 4: Evaluating Model Accuracy ((R^2))

Calculate the Coefficient of Determination ((R^2)) to measure goodness-of-fit:

MATLAB
SS_res = sum((y - y_fit).^2);
SS_tot = sum((y - mean(y)).^2);
R_squared = 1 - (SS_res / SS_tot);
fprintf('R-squared (R^2): %.4f ', R_squared);
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

Physics-Informed Neural Networks (PINNs) for Microgrid Dynamics and Power Flow in MATLAB

Modern microgrids operate with low physical inertia, rapid inverter switching dynamics, and intermittent renewable power generation. Simulating these systems requir...

MATLAB Guide 5 Min Read

ROS 2 and MATLAB Co-Simulation for Autonomous Mobile Robot Path Tracking Using NMPC

Tracking complex trajectories with non-holonomic mobile robots requires handling physical constraints such as actuator saturation, wheel slip, and sharp cornering. Standard cont...