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.
Define predictor variable vector x and response variable vector y:
x = [1 2 3 4 5 6];
y = [2.2 2.8 3.6 4.5 5.1 5.9];% 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);% 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);% Fit LinearModel object mdl = fitlm(x, y);
disp(mdl);Compute fitted values y_fit and plot the linear regression fit against raw data:
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;Calculate the Coefficient of Determination ((R^2)) to measure goodness-of-fit:
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);Real feedback from students across top engineering universities worldwide.
“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!”
“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!”
Explore deep-dive technical articles written by our engineering team to master complex MATLAB & Simulink topics.
Modern microgrids operate with low physical inertia, rapid inverter switching dynamics, and intermittent renewable power generation. Simulating these systems requir...
Tracking complex trajectories with non-holonomic mobile robots requires handling physical constraints such as actuator saturation, wheel slip, and sharp cornering. Standard cont...