基于eigen计算矩阵的特征值和特征向量

有点小瑕疵,就是读取文件和生成文件的位置!备注下本文是在Ubuntu系统下构建的,一些地方可能存在着差异。

1 首先是在如下的文件下建立data.txt

 这个文件与源程序的文件在同一个目录下,其中data.txt的数据及其格式如下:

 2 程序

#include <iostream>
#include <fstream>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>

using namespace std;
using namespace Eigen;

int LEN=4;

int main()
{

    //MatrixXd m(LEN,LEN);
    MatrixXd mm(LEN,LEN);  //数据类型必须是整型
    
    //读取txt数据。
//    m <<  1, 2, 3, 4,
//          5, 6, 7, 8,
//          9,10,11,12,
//         13,14,15,16;


    ifstream in("data.txt");  //读取存有数据的txt文件

    if(!in.is_open ())
            cout << "打开失败!" << endl;  //如果读取失败,则打印“打开失败!”
    
    while (!in.eof())  //若未到文件结束一直循环,读取文本数据到mm
        {
            for(int a=0;a<LEN;a++)
                for(int b=0;b<LEN;b++)
                {
                    in >> mm(a,b);
                }
        }
    

    cout << "读取的数据是:" << endl;
    cout << mm.block(0,0,LEN,LEN) << endl << endl;  //打印出读取的数据


    EigenSolver<Matrix4d> es(m);//计算数据,注意修改维度(下面的4)
    cout << "特征值:" << endl << es.eigenvalues() << endl << endl;
    cout << "特征向量:" << endl << es.eigenvectors() << endl << endl;


    ofstream outfile1;
    ofstream outfile2;
    string valuesFileName("values.txt"); //特征值所在的txt文件
    string vectorsFileName("vectors.txt"); //特征向量所在的txt文件

    outfile1.open(valuesFileName, ostream::app);  //以添加模式打开文件
    outfile2.open(vectorsFileName, ostream::app);  //以添加模式打开文件
    outfile1 << es.eigenvalues();
    outfile2 << es.eigenvectors();


    outfile1.close();  //关闭文件
    outfile2.close();  //关闭文件

    return 0;

}

3 解释

注释这么清楚,不解释!

4 结果

特征值和特征向量最后会输出到values.txt和vecors.txt文件中。

猜你喜欢

转载自blog.csdn.net/qq_27806947/article/details/85058428