雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

C++ Eigen庫計算矩陣特征值及特征向量

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

本文主要講解利用Eigen庫計算矩陣的特征值及特征向量并與Matlab計算結(jié)果進行比較。

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();
 
}

計算結(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計算結(jié)果

使用sort()函數(shù)對特征值排序

主成份分析以及許多應(yīng)用時候,需要對特征值大小排列。

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é)語

本人是在實驗中利用Eigen庫求取最小特征值對應(yīng)特征向量做PCA分析時使用,曾經(jīng)再不知道有Eigen庫的情況下自己寫過矩陣相關(guān)運算的模板類,現(xiàn)在接觸到Eigen庫,就把困擾過自己的問題今天做一個小小總結(jié)。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

上一篇:C/C++實現(xiàn)三路快速排序算法原理

欄    目:C語言

下一篇:C語言控制臺應(yīng)用程序GDI繪制正弦曲線

本文標(biāo)題:C++ Eigen庫計算矩陣特征值及特征向量

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/266.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有