Eigen 线性问题求解(最小二乘等)
程序员文章站
2022-07-12 14:10:50
...
介绍如何求解线性系统,计算几种分解,比如LU,QR,SVD等。
基本的线性求解
问题:假设有一个系统方程写成如下矩阵的形式
Ax=b
其中A,b是矩阵,b也可以是向量,当想要求解x时,可以选择多种分解方式,取决于矩阵A的形式以及考虑的速度和精度,下面是一个简单的例子。
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
Matrix3f A;
Vector3f b;
A << 1,2,3, 4,5,6, 7,8,10;
b << 3, 3, 4;
cout << "Here is the matrix A:\n" << A << endl;
cout << "Here is the vector b:\n" << b << endl;
Vector3f x = A.colPivHouseholderQr().solve(b);
cout << "The solution is:\n" << x << endl;
}
求解为:
Here is the matrix A:
1 2 3
4 5 6
7 8 10
Here is the vector b:
3
3
4
The solution is:
-2
1
1
例子中colPivHouseholderQr()方法返回一个类ColPivHouseholderQR的对象,因此那句话也可以写成
ColPivHouseholderQR<Matrix3f> dec(A);
Vector3f x = dec.solve(b);
这里ColPivHouseholderQR是QR分解的意思,适用于各种矩阵并且速度够快,下面是几种分解的对比
Decomposition | Method | Requirements on the matrix | Speed (small-to-medium) | Speed (large) | Accuracy |
---|---|---|---|---|---|
PartialPivLU | partialPivLu() | Invertible | ++ | ++ | + |
FullPivLU | fullPivLu() | None | - | - - | +++ |
HouseholderQR | householderQr() | None | ++ | ++ | + |
ColPivHouseholderQR | colPivHouseholderQr() | None | ++ | - | +++ |
FullPivHouseholderQR | fullPivHouseholderQr() | None | - | - - | +++ |
LLT | lt() | Positive | definite | +++ | +++ |
LDLT | ldlt() | Positive or negative semidefinite | +++ | + | ++ |
JacobiSVD | jacobiSvd() | None | - - | - - - | +++ |
以上分解都提供了solve()方法。比如当矩阵是正定的时候,表中说明LLT和LDLT是不错的选择。