## C++Eigen库计算矩阵特征值及特征向量

2020年02月14日 编程语言 ⁄ 共 1665字 ⁄ 字号 评论关闭

C++Eigen库代码

#include <iostream>#include <Eigen/Dense>#include <Eigen/Eigenvalues>using namespace Eigen;using namespace std;void Eig(){ Matrix3d A; A << 1, 2, 3, 4, 5, 6, 7, 8, 9; cout << "Here is a 3x3 matrix, A:" << endl << A << endl << endl; EigenSolver<Matrix3d> es(A); Matrix3d D = es.pseudoEigenvalueMatrix(); Matrix3d V = es.pseudoEigenvectors(); cout << "The pseudo-eigenvalue matrix D is:" << endl << D << endl; cout << "The pseudo-eigenvector matrix V is:" << endl << V << endl; cout << "Finally, V * D * V^(-1) = " << endl << V * D * V.inverse() << endl;}int main(){ Eig(); }

//maxCoeff//minCoeffint col_index, row_index;cout << D.maxCoeff(&row_index, &col_index) << endl;cout << row_index << " " << col_index << endl;

Matlab 代码

clear allclcA = [1 2 3;4 5 6;7 8 9][V,D] = eig(A)

Matlab计算结果

A = magic(6);[V,D] = eig(A)[D_S,index] = sort(diag(D),'descend')V_S = V(:,index)

V = 0.4082 -0.2887 0.4082 0.1507 0.4714 -0.4769 0.4082 0.5774 0.4082 0.4110 0.4714 -0.4937 0.4082 -0.2887 0.4082 -0.2602 -0.2357 0.0864 0.4082 0.2887 -0.4082 0.4279 -0.4714 0.1435 0.4082 -0.5774 -0.4082 -0.7465 -0.4714 0.0338 0.4082 0.2887 -0.4082 0.0171 0.2357 0.7068D = 111.0000 0 0 0 0 0 0 27.0000 0 0 0 0 0 0 -27.0000 0 0 0 0 0 0 9.7980 0 0 0 0 0 0 -0.0000 0 0 0 0 0 0 -9.7980D_S = 111.0000 27.0000 9.7980 -0.0000 -9.7980 -27.0000V_S = 0.4082 -0.2887 0.1507 0.4714 -0.4769 0.4082 0.4082 0.5774 0.4110 0.4714 -0.4937 0.4082 0.4082 -0.2887 -0.2602 -0.2357 0.0864 0.4082 0.4082 0.2887 0.4279 -0.4714 0.1435 -0.4082 0.4082 -0.5774 -0.7465 -0.4714 0.0338 -0.4082 0.4082 0.2887 0.0171 0.2357 0.7068 -0.4082