Concatenate sparse matrix Eigen

后端 未结 3 540
闹比i
闹比i 2021-01-21 13:13

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         


        
3条回答
  •  情歌与酒
    2021-01-21 13:48

    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.

提交回复
热议问题