c++sparse-matrixeigen

Concatenate sparse matrix Eigen


I have two sparse matrices in Eigen, and I would like to join them vertically into one. As an example the target of the code would be:

SparseMatrix<double> matrix1;
matrix1.resize(10, 10);
SparseMatrix<double> matrix2;
matrix2.resize(5, 10);

SparseMatrix<double> MATRIX_JOIN;
MATRIX_JOIN.resize(15, 10);
MATRIX_JOIN << matrix1, matrix2;

I found some solutions on a forum however, I wasn't able to implement it.

What's the proper way to join the matrices vertically?

Edit

My implementation:

SparseMatrix<double> L;
SparseMatrix<double> C;
// ... (Operations with the matrices)
SparseMatrix<double> EMATRIX;
EMATRIX.resize(L.rows() + C.rows(), L.cols());
EMATRIX.middleRows(0, L.rows()) = L;
EMATRIX.middleRows(L.rows(), C.rows()) = C;

I get an error of types, acording to the compiler the right hand side is an Eigen::Block and the left side is Eigen::SparseMatrix


Solution

  • As far as I know, there is currently no built-in solution. You can be way more efficient than your solution by using the internal insertBack function:

    SparseMatrix<double> M(L.rows() + C.rows(), L.cols());
    M.reserve(L.nonZeros() + C.nonZeros());
    for(Index c=0; c<L.cols(); ++c)
    {
        M.startVec(c); // Important: Must be called once for each column before inserting!
        for(SparseMatrix<double>::InnerIterator itL(L, c); itL; ++itL)
             M.insertBack(itL.row(), c) = itL.value();
        for(SparseMatrix<double>::InnerIterator itC(C, c); itC; ++itC)
             M.insertBack(itC.row()+L.rows(), c) = itC.value();
    }
    M.finalize();