MATLAB线性回归代码
时间: 2023-09-07 11:13:47 浏览: 32
Sure! Here's an example of MATLAB code for performing linear regression:
```matlab
% Input data
x = [1, 2, 3, 4, 5]; % independent variable
y = [2, 4, 5, 4, 5]; % dependent variable
% Perform linear regression
coefficients = polyfit(x, y, 1); % fit a first-degree polynomial (line) to the data
% Extract slope and intercept
slope = coefficients(1);
intercept = coefficients(2);
% Plot the data and the linear regression line
scatter(x, y, 'filled');
hold on;
x_fit = min(x):max(x);
y_fit = polyval(coefficients, x_fit);
plot(x_fit, y_fit, 'r');
hold off;
% Display the equation of the line
equation = sprintf('y = %.2fx + %.2f', slope, intercept);
disp(equation);
```
This code fits a straight line to a set of data points `(x, y)` using the least squares method. It then plots the data points and the regression line, and displays the equation of the line.