C++ Eigen庫計算矩陣特徵值及特徵向量
阿新 • • 發佈:2018-12-31
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();
}
計算結果:
Matlab 程式碼
clear all
clc
A = [1 2 3;4 5 6;7 8 9]
[V,D] = eig(A)
Matlab計算結果
使用sort()函式對特徵值排序
主成份分析以及許多應用時候,需要對特徵值大小排列。
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.7068
D =
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.7980
D_S =
111.0000
27.0000
9.7980
-0 .0000
-9.7980
-27.0000
V_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
結語
本人是在實驗中利用Eigen庫求取最小特徵值對應特徵向量做PCA分析時使用,曾經再不知道有Eigen庫的情況下自己寫過矩陣相關運算的模板類,現在接觸到Eigen庫,就把困擾過自己的問題今天做一個小小總結。