#include<iostream> #include<Eigen/Dense> usingnamespace std; usingnamespace Eigen; intmain() { Matrix2f A; A << 1, 2, 2, 3; cout << "Here is the matrix A:\n" << A << endl; SelfAdjointEigenSolver<Matrix2f> eigensolver(A); if (eigensolver.info() != Success) abort(); cout << "The eigenvalues of A are:\n" << eigensolver.eigenvalues() << endl; cout << "Here's a matrix whose columns are eigenvectors of A \n" << "corresponding to these eigenvalues:\n" << eigensolver.eigenvectors() << endl; }
运算结果如下:
1 2 3 4 5 6 7 8 9 10
Here is the matrix A: 1 2 2 3 The eigenvalues of A are: -0.236 4.24 Here's a matrix whose columns are eigenvectors of A corresponding to these eigenvalues: -0.851 -0.526 0.526 -0.851
#include<iostream> #include<Eigen/Dense> usingnamespace std; usingnamespace Eigen; intmain() { Matrix2f A, b; LLT<Matrix2f> llt; A << 2, -1, -1, 3; b << 1, 2, 3, 1; cout << "Here is the matrix A:\n" << A << endl; cout << "Here is the right hand side b:\n" << b << endl; cout << "Computing LLT decomposition..." << endl; llt.compute(A); cout << "The solution is:\n" << llt.solve(b) << endl; A(1,1)++; cout << "The matrix A is now:\n" << A << endl; cout << "Computing LLT decomposition..." << endl; llt.compute(A); cout << "The solution is now:\n" << llt.solve(b) << endl; }
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Here is the matrix A: 2 -1 -1 3 Here is the right hand side b: 1 2 3 1 Computing LLT decomposition... The solution is: 1.2 1.4 1.4 0.8 The matrix A is now: 2 -1 -1 4 Computing LLT decomposition... The solution is now: 1 1.29 1 0.571
也可以通过向构造函数中传入矩阵大小来预分配分解矩阵所需要的内存空间大小:
1 2 3
HouseholderQR<MatrixXf> qr(50,50); MatrixXf A = MatrixXf::Random(50,50); qr.compute(A); // no dynamic memory allocation
#include<iostream> #include<Eigen/Dense> usingnamespace std; usingnamespace Eigen; intmain() { Matrix3f A; A << 1, 2, 5, 2, 1, 4, 3, 0, 3; cout << "Here is the matrix A:\n" << A << endl; FullPivLU<Matrix3f> lu_decomp(A); cout << "The rank of A is " << lu_decomp.rank() << endl; cout << "Here is a matrix whose columns form a basis of the null-space of A:\n" << lu_decomp.kernel() << endl; cout << "Here is a matrix whose columns form a basis of the column-space of A:\n" << lu_decomp.image(A) << endl; // yes, have to pass the original A }
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13
Here is the matrix A: 1 2 5 2 1 4 3 0 3 The rank of A is 2 Here is a matrix whose columns form a basis of the null-space of A: 0.5 1 -0.5 Here is a matrix whose columns form a basis of the column-space of A: 5 1 4 2 3 3
#include<iostream> #include<Eigen/Dense> usingnamespace std; usingnamespace Eigen; intmain() { Matrix2d A; A << 2, 1, 2, 0.9999999999; FullPivLU<Matrix2d> lu(A); cout << "By default, the rank of A is found to be " << lu.rank() << endl; lu.setThreshold(1e-5); cout << "With threshold 1e-5, the rank of A is found to be " << lu.rank() << endl; }
输出:
1 2
By default, the rank of A is found to be 2 With threshold 1e-5, the rank of A is found to be 1