//行向量,没个vector<T>特征向量
#include <iostream>
#include <vector>#include <highgui.h>
#include <cv.h>
using namespace std;
typedef vector<vector<double>> martix;
template<class T>
void GetEigenMat( vector<vector<T>> &k , vector<vector<T>> &eigenVec, vector<T> &eigenVal)
{
CvMat* M = cvCreateMat(k.size(),k.size(),CV_32FC1);
cvZero(M);
for(int i = 0; i < k.size(); i++)
for(int j = 0; j < k.size(); j++)
cvmSet(M, i, j, k[i][j]);
CvMat* E = cvCreateMat(k.size(), k.size(), CV_32FC1);
cvZero(E);
CvMat* I = cvCreateMat(k.size(), 1, CV_32FC1);
cvZero(I);
//从矩阵M中获取特征向量存入E(降序排列),特征值存入I
cvEigenVV(M, E, I, DBL_EPSILON);
vector<T> a(k.size(),0);
vector< vector<T> > eigenMat(3,a);
vector<T> eigenValueMat(a);
//取前两个最大的特征向量
vector<T> _line;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < k.size(); j++){
_line.push_back((double)cvmGet(E,i,j));
}
eigenVec.push_back(_line);
_line.clear();
}
for(int i = 0; i < 3; i++)
eigenVal.push_back((T)cvmGet(I, i, 0));
FILE *fp1 = NULL;
fp1 = fopen("eigenValues.txt", "w");
for (int i = 0; i < 3; i++)
{
fprintf_s(fp1,"%lf ", eigenVal[i]);
}
fclose(fp1);
cvReleaseMat(&M);
cvReleaseMat(&E);
cvReleaseMat(&I);
}
int main(void)
{
vector<vector<double>> Matr;
vector<vector<double>> eigenVector;
vector<double> eigenValue;
FILE * fp = fopen("./m.txt", "r");
int w, h;
fscanf(fp, "%d %d\n", &w, &h);
if(w != h){
printf("martix width != height\n");
return 1;
}
double _value;
vector<double> _line;
for (int i = 0; i < h; i++){
for(int j = 0; j < w; j++)
{
fscanf(fp, "%lf ", &_value);
_line.push_back(_value);
}
Matr.push_back(_line);
_line.clear();
}
fclose(fp);
GetEigenMat(Matr, eigenVector, eigenValue);
FILE *fp1 = NULL;
fp1 = fopen("eigen.txt", "w");
for (int i = 0; i < eigenVector.size(); i++){
for(int j = 0; j < eigenVector.size(); j++)
{
fprintf_s(fp1,"%lf ", eigenVector[i][j]);
}
fputc('\n', fp1);
}
fclose(fp1);
int temp = 10;
}