Linear Regression, line of best fit
조회 수: 422 (최근 30일)
이전 댓글 표시
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"?
댓글 수: 0
답변 (2개)
Jaimin
2024년 8월 16일
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)]);
For more information on “polyfit” function, you can refer to the following documentation.
I hope this helps.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Linear and Nonlinear Regression에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!