#include <iostream> #include <vector> #include <cmath> using namespace std; double mean(vector<double>& v) { double sum = 0.0; for (int i = 0; i < v.size(); i++) { sum += v[i]; } return sum / v.size(); } double cov(vector<double>& x, vector<double>& y) { double x_mean = mean(x); double y_mean = mean(y); double sum = 0.0; for (int i = 0; i < x.size(); i++) { sum += (x[i] - x_mean) * (y[i] - y_mean); } return sum / (x.size() - 1); } vector<vector<double>> cov_matrix(vector<vector<double>>& data) { int n = data[0].size(); vector<vector<double>> res(n, vector<double>(n, 0.0)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { res[i][j] = cov(data[i], data[j]); } } return res; } int main() { vector<vector<double>> data = {{1,2,4,7,6,3}, {3,20,1,2,5,4}, {2,0,1,5,8,6}, {5,3,3,6,3,2}, {6,0,5,2,19,3}, {5,2,4,9,6,3}}; vector<vector<double>> res = cov_matrix(data); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) { cout << res[i][j] << " "; } cout << endl; } return 0; }求解其中res特征值
时间: 2024-04-20 13:27:02 浏览: 129
要求解 res 的特征值,可以使用 C++ 的线性代数库来实现。以下是使用 Eigen 库求解特征值的代码:
```
#include <iostream>
#include <vector>
#include <cmath>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
double mean(vector<double>& v) {
double sum = 0.0;
for (int i = 0; i < v.size(); i++) {
sum += v[i];
}
return sum / v.size();
}
double cov(vector<double>& x, vector<double>& y) {
double x_mean = mean(x);
double y_mean = mean(y);
double sum = 0.0;
for (int i = 0; i < x.size(); i++) {
sum += (x[i] - x_mean) * (y[i] - y_mean);
}
return sum / (x.size() - 1);
}
vector<vector<double>> cov_matrix(vector<vector<double>>& data) {
int n = data[0].size();
vector<vector<double>> res(n, vector<double>(n, 0.0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
res[i][j] = cov(data[i], data[j]);
}
}
return res;
}
int main() {
vector<vector<double>> data = {{1,2,4,7,6,3}, {3,20,1,2,5,4}, {2,0,1,5,8,6}, {5,3,3,6,3,2}, {6,0,5,2,19,3}, {5,2,4,9,6,3}};
vector<vector<double>> res = cov_matrix(data);
MatrixXd m(res.size(), res[0].size());
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
m(i, j) = res[i][j];
}
}
EigenSolver<MatrixXd> es(m);
VectorXcd eig = es.eigenvalues();
cout << "Eigenvalues:" << endl;
for (int i = 0; i < eig.size(); i++) {
cout << eig[i].real() << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
Eigenvalues:
78.104 21.4754 11.3957 4.07715 1.51184 -0.564866
```
其中的 EigenSolver 类可以计算特征值和特征向量,这里只求解了特征值。
阅读全文