本文主要講解利用Eigen庫(kù)計(jì)算矩陣的特征值及特征向量并與Matlab計(jì)算結(jié)果進(jìn)行比較。
C++Eigen庫(kù)代碼
#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(); }計(jì)算結(jié)果:

最大最小特征值及其索引位置
//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計(jì)算結(jié)果

使用sort()函數(shù)對(duì)特征值排序
主成份分析以及許多應(yīng)用時(shí)候,需要對(duì)特征值大小排列。
A = magic(6);[V,D] = eig(A)[D_S,index] = sort(diag(D),'descend')V_S = V(:,index)
結(jié)果
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
結(jié)語(yǔ)
本人是在實(shí)驗(yàn)中利用Eigen庫(kù)求取最小特征值對(duì)應(yīng)特征向量做PCA分析時(shí)使用,曾經(jīng)再不知道有Eigen庫(kù)的情況下自己寫(xiě)過(guò)矩陣相關(guān)運(yùn)算的模板類,現(xiàn)在接觸到Eigen庫(kù),就把困擾過(guò)自己的問(wèn)題今天做一個(gè)小小總結(jié)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答