Linear Regression, line of best fit

182 次查看(过去 30 天)
YM
YM 2019-5-17
回答: Jaimin 2024-8-16,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"?

回答(2 个)

KSSV
KSSV 2019-5-17
To fit a line use n=1.

Jaimin
Jaimin 2024-8-16,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.

类别

Help CenterFile Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by