Clear Filters
Clear Filters

Linear Regression, line of best fit

182 views (last 30 days)
YM
YM on 17 May 2019
Answered: Jaimin on 16 Aug 2024 at 5:13
If I have data for vectors x = [ ] and y= [ ], how do I find and plot the linear regression/line of best fit? Once I have plotted the line of best fit, how do I record the slope of that line of best fit to some variable "a"?

Answers (2)

KSSV
KSSV on 17 May 2019
To fit a line use n=1.

Jaimin
Jaimin on 16 Aug 2024 at 5:13
Hi @YM,
I understand that the goal is to determine the linear regression/line of best fit for a dataset and to find the corresponding slope.
To achieve this, you can use the "polyfit" function. I have included a sample code snippet below for clearer understanding:
% Sample data vectors x and y
x = [1, 2, 3, 4, 5]; % Replace with your data
y = [2, 4, 6, 8, 10]; % Replace with your data
% Find the coefficients of the linear regression (slope and intercept)
coefficients = polyfit(x, y, 1);
% Extract the slope (first coefficient)
a = coefficients(1);
% Generate the values of the line of best fit
y_fit = polyval(coefficients, x);
% Plot the original data
figure;
plot(x, y, 'o', 'DisplayName', 'Data Points'); % Original data points
hold on;
% Plot the line of best fit
plot(x, y_fit, '-', 'DisplayName', 'Line of Best Fit'); % Line of best fit
% Add labels and legend
xlabel('x');
ylabel('y');
title('Linear Regression / Line of Best Fit');
legend show;
% Display the slope in the command window
disp(['The slope of the line of best fit is: ', num2str(a)]);
The slope of the line of best fit is: 2
For more information onpolyfit function, you can refer to the following documentation.
I hope this helps.

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!