Linear Regression, line of best fit

424 visualizaciones (últimos 30 días)
YM
YM el 17 de Mayo de 2019
Respondida: Jaimin el 16 de Ag. de 2024
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"?

Respuestas (2)

KSSV
KSSV el 17 de Mayo de 2019
To fit a line use n=1.

Jaimin
Jaimin el 16 de Ag. de 2024
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.

Categorías

Más información sobre Linear and Nonlinear Regression en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by