c++ vector求m*n阶矩阵平均值、方差、协方差、特征向量、特征值
时间: 2023-07-10 18:40:39 浏览: 152
PCA-方差及协方差等介绍
以下是使用 C++ 的 vector 实现求解 m*n 阶矩阵的平均值、方差、协方差、特征向量和特征值的代码:
```c++
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
int m, n;
cout << "请输入矩阵的行数和列数(空格隔开):" << endl;
cin >> m >> n;
vector<vector<double>> matrix(m, vector<double>(n));
// 输入矩阵
cout << "请输入矩阵的元素(按行输入):" << endl;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
cin >> matrix[i][j];
}
}
// 计算平均值
double average = 0.0;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
average += matrix[i][j];
}
}
average /= m * n;
cout << "平均值为:" << average << endl;
// 计算方差
double variance = 0.0;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
variance += pow(matrix[i][j] - average, 2);
}
}
variance /= m * n;
cout << "方差为:" << variance << endl;
// 计算协方差矩阵
vector<vector<double>> covariance(n, vector<double>(n));
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
covariance[i][j] = 0.0;
for (int k=0; k<m; k++) {
covariance[i][j] += (matrix[k][i] - average) * (matrix[k][j] - average);
}
covariance[i][j] /= m - 1;
}
}
cout << "协方差矩阵为:" << endl;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
cout << covariance[i][j] << " ";
}
cout << endl;
}
// 计算特征值和特征向量
vector<double> eigenvalues(n);
vector<vector<double>> eigenvectors(n, vector<double>(n));
for (int i=0; i<n; i++) {
eigenvectors[i][i] = 1.0;
}
for (int i=0; i<n; i++) {
eigenvalues[i] = covariance[i][i];
}
int max_iter = 100;
double eps = 1e-6;
for (int iter=0; iter<max_iter; iter++) {
double max_eigenv = 0.0;
int max_index = 0;
for (int i=0; i<n; i++) {
if (eigenvalues[i] > max_eigenv) {
max_eigenv = eigenvalues[i];
max_index = i;
}
}
if (max_eigenv < eps) {
break;
}
for (int i=0; i<n; i++) {
eigenvectors[i][max_index] = covariance[i][max_index];
}
for (int i=0; i<n; i++) {
eigenvalues[i] = 0.0;
for (int j=0; j<n; j++) {
eigenvalues[i] += eigenvectors[j][i] * covariance[j][i];
}
}
}
cout << "特征向量为:" << endl;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
cout << eigenvectors[i][j] << " ";
}
cout << endl;
}
cout << "特征值为:" << endl;
for (int i=0; i<n; i++) {
cout << eigenvalues[i] << " ";
}
cout << endl;
return 0;
}
```
要注意的是,vector 的下标是从 0 开始,所以在计算特征向量时需要将对角线上的元素初始化为 1.0。另外,特征值和特征向量的计算方法与使用数组的方法相同。
阅读全文