matlab一元线性回归模型代码
时间: 2023-10-08 08:08:25 浏览: 160
一元线性回归Matlab代码
Sure! Here's an example code for performing simple linear regression in MATLAB:
```matlab
% Input data
x = [1 2 3 4 5]; % Independent variable
y = [2 4 5 4 5]; % Dependent variable
% Calculate linear regression coefficients
n = length(x); % Number of observations
x_mean = mean(x); % Mean of x
y_mean = mean(y); % Mean of y
xy_mean = mean(x .* y); % Mean of x*y
x_sq_mean = mean(x.^2); % Mean of x^2
% Calculate slope (beta_1) and intercept (beta_0)
beta_1 = (xy_mean - x_mean * y_mean) / (x_sq_mean - x_mean^2);
beta_0 = y_mean - beta_1 * x_mean;
% Predict the values
y_pred = beta_0 + beta_1 * x;
% Plot the data and regression line
scatter(x, y, 'filled');
hold on;
plot(x, y_pred, 'r');
xlabel('x');
ylabel('y');
legend('Data', 'Regression line');
title('Linear Regression');
% Print the coefficients
fprintf('Slope (beta_1): %.2f\n', beta_1);
fprintf('Intercept (beta_0): %.2f\n', beta_0);
```
Hope this helps! Let me know if you have any further questions.
阅读全文