Search code examples
c++sparse-matrixeigen

Eigen sparse matrix multiplications seem to compute full matrix


I am trying to multiply 2 eigen sparse matrices. The code is as follows:

Eigen::SparseMatrix<float> SpMat;
SpMat mat_1;
mat_1.resize(n_e, n_e);
... Fill the matrix. It is sparse

SpMat mat_2;
mat_1.resize(n_e, n_e);
... Fill the matrix. It is sparse

SpMat mat_3 = (mat_1 * mat_2).pruned();

This works fine for small matrices but for larger matrices, it just runs and runs and ten crashes with a seg fault. The same thing in Matlab takes a couple of seconds. So, I wonder if it is trying to keep the full matrix somewhere. If it does, that is really bad! I looked at the documentation and doing this is what it suggested to prune the matrix on the fly.


Solution

  • Basically, the document is sightly confusing for me at least.

    the way to do it is simply:

    SpMat mat_3 = mat_1 * mat_2
    

    No dense matrix is created along the way.

    Eigen rocks!