c++协方差矩阵

协方差矩阵是PCA计算中一个重要的计算过程,这里可以参考:http://blog.codinglabs.org/articles/pca-tutorial.html。

代码:

#include <iostream>
#include <vector>
using namespace std;

int My_CalcCovarMatrix(const vector<vector<float>>& mat, vector<vector<float>>& covar, vector<float>& mean)
{
	const int rows = mat.size();
 	const int cols = mat[0].size();

	for (int i = 0; i<cols; i++)   // 计算均值
	 {
	  for (int j = 0; j<rows; j++)
	  {
	   mean[i] += mat[j][i];
	  }
	  mean[i] = 1.0 / (rows) * mean[i];
	 }
		
	vector<vector<float>> mat_mean;
	mat_mean = mat;
	for (int i = 0; i<rows; i++)	//
	 {
	  for (int j = 0; j<cols; j++)
	  {
	   mat_mean[i][j] = mat[i][j] - mean[j];
	  }
	 }
	 
	 for (int i = 0; i<cols; i++)  //矩阵计算
	 {
	  for (int j = 0; j<cols; j++)
	  {
	   for (int k = 0; k < rows; k++)
	   {
	    covar[i][j] += mat_mean[k][i]*mat_mean[k][j];
	   }
	  }
	 }
	 return 0;
	}

int main()
{
	vector<vector<float>> temp;
	vector<float> t;
	t.push_back(1.2f);
	t.push_back(-3.6f);
	t.push_back(4.3f);
	temp.push_back(t);
 	t.clear();
	 t.push_back(2.5f);
	 t.push_back(9.2f);
	 t.push_back(1.3f);
	 temp.push_back(t);
	 t.clear();
	 t.push_back(5.6f);
	 t.push_back(0.5f);
	 t.push_back(9.4f);
	 temp.push_back(t);
	 t.clear();
	 t.push_back(-2.5f);
	 t.push_back(7.2f);
	 t.push_back(-3.4f);
	 temp.push_back(t);
	 t.clear();
	const int rows = temp.size();
	 const int cols = temp[0].size();
	 vector<std::vector<float>> covar;
	 t.push_back(0.0f);
	 t.push_back(0.0f);
	 t.push_back(0.0f);
	 covar.push_back(t);
	 t.clear();
	 t.push_back(0.0f);
	 t.push_back(0.0f);
	 t.push_back(0.0f);
	 covar.push_back(t);
	 t.clear(); 
	 t.push_back(0.0f);
	 t.push_back(0.0f);
	 t.push_back(0.0f);
	 covar.push_back(t);
	 t.clear();
	 
	vector<float> mean;
	 mean.resize(3, (float)0);
	 My_CalcCovarMatrix(temp, covar, mean);
	 for (int i = 0; i<cols; i++)
	 {
	  for (int j = 0; j<cols; j++)
	  {
	   cout << covar[i][j] << " ";
	  }
	  cout << endl;
	 }
	system("pause");
	return 0;
}				
			
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值