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.
% 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; scatter(x, y, 'filled'); lsline; % Adds least-squares line automatically title('Scatter with Linear Regression Line'); mdl = fitlm(x, y); % Creates linear model plot(mdl); % Plots data, fit, and confidence bounds disp(mdl); % Shows R-squared, p-values, coefficients Ideal for data analysis, trend lines, and curve fitting.
“I got full marks on my MATLAB assignment! The solution was perfect and delivered well before the deadline. Highly recommended!”
“Quick delivery and excellent communication. The team really understood the problem and provided a great solution. Will use again.”
Explore how MATLAB Solutions has helped clients achieve their academic and research goals through practical, tailored assistance.
Generative AI in MATLAB is transforming how engineers, scientists, and researchers approach coding, prototyping, and problem-solving. No longer do you need to switch between tools or struggle with syntax MATLAB Copilot, MathWorks' officia
Introduction Not long ago, AI governance was a topic reserved for policy rooms and ethics co