c++使用Eigen库计算矩阵特征值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36219858/article/details/80709619

Eigen
是一个方便使用的c++矩阵运算库,只要包含Eigen的源码头文件,就能使用。
下面的例子是计算矩阵的特征值特征向量,并把特征向量矩阵实部和虚部分开。


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


using namespace std;
using namespace Eigen;


int main()
{

    Matrix3d A;  //定义3*3  double 型矩阵
    A << 1, 2, 3, 5,-5,3,4,6,9;

    cout << "Here is a matrix, A:" << endl << A << endl << endl;
    EigenSolver<MatrixXd> es(A);

    cout << "The eigenvalues of A are:" << endl << es.eigenvalues() << endl;

    MatrixXcd vect = es.eigenvectors();//特征向量矩阵
    cout << "复数形式输出:" << endl << vect << endl;

    MatrixXd realvect(vect.rows(), vect.cols());
    MatrixXd imagvect(vect.rows(), vect.cols());

    cout << "虚实拆分:" << endl;
    /*两种拆分方式等价
    for (size_t i = 0; i < vect.rows(); i++)
    {
        for (size_t j = 0; j < vect.cols(); j++)
        {
            realvect(i, j) = real(vect(i, j));
            imagvect(i, j) = imag(vect(i, j));
        }
    }*/
    for (size_t i = 0; i < vect.size(); i++)
    {
        *(realvect.data() + i) = real(*(vect.data() + i));
        *(imagvect.data() + i) = imag(*(vect.data() + i));
    }

    cout << "realvect:" << endl << realvect << endl;
    cout << "imagvect:" << endl << imagvect << endl;

}

猜你喜欢

转载自blog.csdn.net/sinat_36219858/article/details/80709619