Linear Regression, line of best fit

424 ビュー (過去 30 日間)
YM
YM 2019 年 5 月 17 日
回答済み: Jaimin 2024 年 8 月 16 日
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 日
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 Center および File ExchangeLinear 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