Eigen學習之簡單線性方程與矩陣分解


  Eigen提供了解線性方程的計算方法,包括LU分解法,QR分解法,SVD(奇異值分解)、特征值分解等。對於一般形式如下的線性系統:

        

  解決上述方程的方式一般是將矩陣A進行分解,當然最基本的方法是高斯消元法。

  先來看Eigen 官方的第一個例程:

 1 #include <iostream>
 2 #include <Eigen/Dense>
 3 
 4 using namespace std;
 5 using namespace Eigen;
 6 
 7 int main()
 8 {
 9     Matrix3f A;
10     Vector3f b;
11     A << 1,2,3, 4,5,6, 7,8,10;
12     b << 3,3,4;
13     cout<<"Here is the Matrix A:\n"<< A <<endl;
14     cout<<" Here is the vector b:\n"<< b <<endl;
15     Vector3f x = A.colPivHouseholderQr().solve(b);
16     cout<<"The solution is:\n"<<x<<endl;
17     return 0;
18 }

運行結果如下:

Eigen內置的解線性方程組的算法如下表所示:

 

使用這些接口也可以解決矩陣相乘的問題:

 1 #include <iostream>
 2 #include <Eigen/Dense>
 3 
 4 using namespace std;
 5 using namespace Eigen;
 6 
 7 int main()
 8 {
 9     Matrix2f A,b;
10     A << 2,-1,-1,3;
11     b << 1,2,3,1;
12     cout<<"Here is the matrix A:\n"<<A<<endl;
13     cout<<"Here is the right hand side b:\n"<<b<<endl;
14     Matrix2f x = A.ldlt().solve(b);
15     cout<<"The solution is:\n"<<x<<endl;
16     return 0;
17 }



運行結果如下:

 

Eigen也提供了計算特征值和特征向量的算法:

下面是一個簡單的例子:

 1 #include <iostream>
 2 #include <Eigen/Dense>
 3 
 4 using namespace std;
 5 using namespace Eigen;
 6 
 7 int main()
 8 {
 9     Matrix2f A;
10     A << 1,2,2,3;
11     cout<<"Here is the matrix A:\n"<<A<<endl;
12     SelfAdjointEigenSolver<Matrix2f> eigensolver(A);
13     if( eigensolver.info() != Success ) abort();
14     cout<<" The eigenvalues of A are:\n"<<eigensolver.eigenvalues()<<endl;
15     cout<<" Here is a matrix whose columns are eigenvectors of A\n"
16         <<" corresponding to these eigenvalues:\n"
17         <<eigensolver.eigenvectors()<<endl;
18     return 0;
19 }

運行結果如下:

 

Eigen 也提供了求逆矩陣和求矩陣行列式的算法,但是這兩種算法對於大型矩陣來說都是非常不經濟的算法,當需要對大型矩陣做這種的操作時,需要自己判斷到底需不需這樣做。但是對於小型矩陣 則可以沒有顧慮地使用。

下面是一個例子:

 1 #include <iostream>
 2 #include <Eigen/Dense>
 3 
 4 using namespace std;
 5 using namespace Eigen;
 6 
 7 int main()
 8 {
 9     Matrix3f A;
10     A << 1,2,1,
11          2,1,0,
12          -1,1,2;
13 
14     cout<<"Here is the matrix A:\n"<<A<<endl;
15     cout<<"The determinant of A is "<<A.determinant()<<endl;
16     cout<<"The inverse of A is:\n"<<A.inverse()<<endl;
17     return 0;
18 }

運行結果如下:

 

Eigen也提供了解最小二乘問題的解法,並給出兩種實現,分別是BDCSVD和JacobiSVD,其中推薦使用的一種是BDCSVD。下面是一個例子:

 1 #include <iostream>
 2 #include <Eigen/Dense>
 3 
 4 using namespace std;
 5 using namespace Eigen;
 6 
 7 int main()
 8 {
 9     MatrixXf A = MatrixXf::Random(3,2);
10     cout<<"Here is the matrix A:\n"<<A<<endl;
11     VectorXf b = VectorXf::Random(3);
12     cout<<"Here is the right hand side b:\n"<<b<<endl;
13     cout<<"The least-squares solution is:\n"
14         <<A.bdcSvd(ComputeThinU|ComputeThinV).solve(b)<<endl;
15     return 0;
16 }

運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM