Search code examples
c++linear-algebrasparse-matrixeigen

Can I solve a system of linear equations, in the form Ax = b with A being sparse, using Eigen?


I need to convert a MATLAB code into C++, and I'm stuck with this instruction:

a = K\F

, where K is a sparse matrix of size n x n, and F is a column vector of size n.

I know it's easy to solve that using the Eigen library - I have tried the fullPivLu() method, and I've been able to built a working snippet, using a Matrix and a Vector.

However, my K is a SparseMatrix<double> (while F is a VectorXd). My declarations:

SparseMatrix<double> K(nec, nec);   
VectorXd F(nec);

and it seems that SparseMatrix doesn't have the fullPivLu() method, nor the lu() one.

I've tried, in fact, these two different approaches, taken from the documentation:

//1.
MatrixXd x = K.fullPivLu().solve(F);
//2.
VectorXf x;
K.lu().solve(F, &x);

They don't work, because fullPivLu() and lu() are not members of 'Eigen::SparseMatrix<_Scalar>'

So, I am asking: is there a way to solve a system of linear equations (the MATLAB's mldivide, or '\'), using Eigen for C++, with K being a sparse matrix?

Thank you for any help.


Solution

  • Would Eigen::SparseLU work for you?