我是靠谱客的博主 高贵悟空,这篇文章主要介绍基于eigen计算矩阵的特征值和特征向量,现在分享给大家,希望可以做个参考。

有点小瑕疵,就是读取文件和生成文件的位置!备注下本文是在Ubuntu系统下构建的,一些地方可能存在着差异。

1 首先是在如下的文件下建立data.txt

 这个文件与源程序的文件在同一个目录下,其中data.txt的数据及其格式如下:

 2 程序

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream> #include <fstream> #include <Eigen/Dense> #include <Eigen/Eigenvalues> using namespace std; using namespace Eigen; int LEN=4; int main() { //MatrixXd m(LEN,LEN); MatrixXd mm(LEN,LEN); //数据类型必须是整型 //读取txt数据。 // m << 1, 2, 3, 4, // 5, 6, 7, 8, // 9,10,11,12, // 13,14,15,16; ifstream in("data.txt"); //读取存有数据的txt文件 if(!in.is_open ()) cout << "打开失败!" << endl; //如果读取失败,则打印“打开失败!” while (!in.eof()) //若未到文件结束一直循环,读取文本数据到mm { for(int a=0;a<LEN;a++) for(int b=0;b<LEN;b++) { in >> mm(a,b); } } cout << "读取的数据是:" << endl; cout << mm.block(0,0,LEN,LEN) << endl << endl; //打印出读取的数据 EigenSolver<Matrix4d> es(m);//计算数据,注意修改维度(下面的4) cout << "特征值:" << endl << es.eigenvalues() << endl << endl; cout << "特征向量:" << endl << es.eigenvectors() << endl << endl; ofstream outfile1; ofstream outfile2; string valuesFileName("values.txt"); //特征值所在的txt文件 string vectorsFileName("vectors.txt"); //特征向量所在的txt文件 outfile1.open(valuesFileName, ostream::app); //以添加模式打开文件 outfile2.open(vectorsFileName, ostream::app); //以添加模式打开文件 outfile1 << es.eigenvalues(); outfile2 << es.eigenvectors(); outfile1.close(); //关闭文件 outfile2.close(); //关闭文件 return 0; }

3 解释

注释这么清楚,不解释!

4 结果

特征值和特征向量最后会输出到values.txt和vecors.txt文件中。

最后

以上就是高贵悟空最近收集整理的关于基于eigen计算矩阵的特征值和特征向量的全部内容,更多相关基于eigen计算矩阵内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部