c++ 求输入的矩阵的协方差矩阵
程序员文章站
2024-03-17 20:03:52
...
参考知识点:
1、这个说的非常详细:协方差矩阵计算方法
( 推荐手动求解他的例子)
代码:
#include <iostream>
#include<vector>
#include<fstream>
using namespace std;
int main()
{
int m, n;
cout << "请输入矩阵的行、列数:" << endl;
cin >> m >> n;
vector<vector<double>> matrix(m, vector<double>(n));
vector<vector<double>> matrixT(n, vector<double>(m));
cout << "输入矩阵中:" << endl;
ifstream fin("inputData.txt");
double input;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
fin >> input;
matrix[i][j] = input;
matrixT[j][i] = input;
}
//均值向量
vector<double> E(n);
for (int j = 0; j < n; ++j)
{
double sum = 0;
for (int i = 0; i < m; ++i)
{
sum += matrix[i][j];
}
E[j] = sum / m;
}
//样本中心化矩阵
vector<vector<double>> centerMatrix(m, vector<double>(n));
vector<vector<double>> centerMatrixT(n, vector<double>(m));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
centerMatrix[i][j] = matrix[i][j] - E[j];
centerMatrixT[j][i] = centerMatrix[i][j];
}
//协方差矩阵:covMatrix = 1 / (m-1) * matrixT * matrix
vector<vector<double>> covMatrix(n, vector<double>(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < m; ++k)
covMatrix[i][j] += centerMatrixT[i][k] * centerMatrix[k][j];
cout << endl << "协方差矩阵为:" << endl;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
cout << covMatrix[i][j] / (m - 1.0) << " ";
cout << endl<<endl;
}
return 0;
}
代码使用方法:
- 1、在代码文件的文件夹下新建文件 inputData.txt
- 2、输入数据
以下数据为10行20列
输出:
说明:
1、你自己可以自定义输入矩阵的大小:在 inputData.txt 文件下修改数据并在运行时在控制台正确输入矩阵的行、列数。
上一篇: 安卓数据存储之SharedPreferences存储
下一篇: 协方差矩阵—黑塞矩阵—正定矩阵