计算皮尔逊相关系数matlab源代码
时间: 2023-11-04 10:49:23 浏览: 54
Sure! Here's a MATLAB code snippet to calculate the Pearson correlation coefficient:
```matlab
% Data
x = [1, 2, 3, 4, 5];
y = [2, 4, 6, 8, 10];
% Calculate mean
mean_x = mean(x);
mean_y = mean(y);
% Calculate standard deviation
std_x = std(x);
std_y = std(y);
% Calculate covariance
covariance = cov(x, y);
% Calculate Pearson correlation coefficient
pearson_coefficient = covariance(1, 2) / (std_x * std_y);
% Display the result
disp(['Pearson correlation coefficient: ', num2str(pearson_coefficient)]);
```
In this code, `x` and `y` represent two sets of data. We first calculate the mean and standard deviation of each set using the `mean()` and `std()` functions, respectively. Then we calculate the covariance between `x` and `y` using the `cov()` function. Finally, we divide the covariance by the product of the standard deviations to obtain the Pearson correlation coefficient.
Please note that the code assumes that the lengths of `x` and `y` are the same.