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

Eigen库的配置比较容易,可以参考博客http://blog.csdn.net/abcjennifer/article/details/7781936中的相关内容。关于Eigen库的矩阵±×运算可参考:http://blog.csdn.net/augusdi/article/details/12907341中的相关内容。本文主要讲解利用Eigen库计算矩阵的特征值及特征向量并与Matlab计算结果进行比较。

Eigen库下载

Eigen库官网:http://eigen.tuxfamily.org/index.php?title=Main_Page#Download
在这里插入图片描述

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
      //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计算结果
在这里插入图片描述

使用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库,就把困扰过自己的问题今天做一个小小总结。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值