Eigen稀疏矩阵求解线性方程,内建的有直接求解器,迭代求解器和第三方求解器。见文档http://eigen.tuxfamily.org/dox/group__TopicSparseSystems.html
图二见链接https://blog.youkuaiyun.com/xuezhisdc/article/details/54634080
这里是使用Eigen里的迭代求解器,因为矩阵非方阵,也不是对称的,选择LeastSquaresConjugateGradient。
1、包含头文件#include "Eigen/Sparse"
#include "Eigen/IterativeLinearSolvers"
2、稀疏矩阵填充,把非零元素填入即可,有直接插入法和Triplet方式插入法。Triplet方式速度快。
// 默认是按列优先
Eigen::SparseMatrix<float> A1_sparse(A_rows, A_cols);
Eigen::VectorXf b1_sparse(b_rows, b_cols);
Eigen::VectorXf x1_sparse;
std::vector<Eigen::Triplet<float>> tripletlist;
for (int i = 0; i < A_rows; i++)
{
for (int j = 0; j < A_cols; j++)
{
if (A(i, j) != 0)
{
//按Triplet方式填充,速度快
tripletlist.push_back(Eigen::Triplet<float>(i, j, A(i, j)));
// 直接插入速度慢
//A1_sparse.insert(i, j) = A(i, j);
}
}
}
A1_sparse.setFromTriplets(tripletlist.begin(), tripletlist.end());
// 压缩优化矩阵
A1_sparse.makeCompressed();
Eigen::LeastSquaresConjugateGradient<Eigen::SparseMatrix<float> > Solver_sparse;
// 设置迭代精度
Solver_sparse.setTolerance(0.001);
Solver_sparse.compute(A1_sparse);
//x1_sparse 即为解
x1_sparse = Solver_sparse.solve(b1_sparse);