C++ Eigen庫(kù)計(jì)算矩陣特征值及特征向量
本文主要講解利用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 //minCoeff int col_index, row_index; cout << D.maxCoeff(&row_index, &col_index) << endl; cout << row_index << " " << col_index << endl;
Matlab 代碼
clear all clc A = [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.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
結(jié)語
本人是在實(shí)驗(yàn)中利用Eigen庫(kù)求取最小特征值對(duì)應(yīng)特征向量做PCA分析時(shí)使用,曾經(jīng)再不知道有Eigen庫(kù)的情況下自己寫過矩陣相關(guān)運(yùn)算的模板類,現(xiàn)在接觸到Eigen庫(kù),就把困擾過自己的問題今天做一個(gè)小小總結(jié)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
DSP中浮點(diǎn)轉(zhuǎn)定點(diǎn)運(yùn)算--浮點(diǎn)與定點(diǎn)概述
本文主要介紹DSP中浮點(diǎn)與定點(diǎn)概述,很值得學(xué)習(xí)一下,需要的朋友可以參考一下。2016-06-06
C++map,set,multiset,multimap詳細(xì)解析
在C++標(biāo)準(zhǔn)模板庫(kù)(STL)中,容器分為關(guān)聯(lián)式容器和序列式容器兩大類,關(guān)聯(lián)式容器主要包括set、map、multiset和multimap,通過索引來訪問元素,本文給大家介紹C++?map,set,multiset,multimap的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2024-09-09
C++實(shí)現(xiàn)圖像目標(biāo)區(qū)裁剪ImageCropping
本文主要介紹了C++實(shí)現(xiàn)圖像目標(biāo)區(qū)裁剪ImageCropping,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
Visual Studio 2022無法打開源文件的解決方式
這篇文章主要介紹了Visual Studio 2022無法打開源文件的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01

