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
I ended up doing the following:
MATRIX_JOIN.resize(matrix1.rows() + matrix2.rows(), matrix1.cols() + matrix2.cols());
MATRIX_JOIN.setZero();
// Fill MATRIX_JOIN with triples from the other matrices
std::vector > tripletList;
for (int k = 0; k < matrix1.outerSize(); ++k)
{
for (SparseMatrix::InnerIterator it(matrix1, k); it; ++it)
{
tripletList.push_back(Triplet(it.row(), it.col(), it.value()));
}
}
for (int k = 0; k < matrix2.outerSize(); ++k)
{
for (SparseMatrix::InnerIterator it(matrix2, k); it; ++it)
{
tripletList.push_back(Triplet(it.row(), it.col(), it.value()));
}
}
FINALMATRIX.setFromTriplets(tripletList.begin(), tripletList.end());
There can be a speedup by calling tripleList.reserve(X)
with X being the expected amount of triplets to insert.