Concatenate sparse matrix Eigen

后端 未结 3 544
闹比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:35

    Based on @Javier's answer.

    • Fixed the number of columns in the output matrix (just cols instead of cols+cols)
    • Fixed the lower matrice's triplet indices (upper.rows() + it.row() instead of just it.row())

    using sparse_matrix_type = Eigen::SparseMatrix;
    using triplet_type = Eigen::Triplet;
    
    static sparse_matrix_type sparse_vstack(sparse_matrix_type const& upper, sparse_matrix_type const& lower) {
      assert(upper.cols() == lower.cols() && "vstack with mismatching number of columns");
    
      std::vector triplets;
      triplets.reserve(upper.nonZeros() + lower.nonZeros());
    
      for (int k = 0; k < upper.outerSize(); ++k) {
        for (sparse_matrix_type::InnerIterator it(upper, k); it; ++it) {
          triplets.emplace_back(it.row(), it.col(), it.value());
        }
      }
    
      for (int k = 0; k < lower.outerSize(); ++k) {
        for (sparse_matrix_type::InnerIterator it(lower, k); it; ++it) {
          triplets.emplace_back(upper.rows() + it.row(), it.col(), it.value());
        }
      }
    
      sparse_matrix_type result(lower.rows() + upper.rows(), upper.cols());
      result.setFromTriplets(triplets.begin(), triplets.end());
      return result;
    }
    

    Unfortunately I coulnd't get @chtz's example to work with Eigen 3.3.4 due to a static assertion error THIS_SPARSE_BLOCK_SUBEXPRESSION_IS_READ_ONLY. It seems to be explicitly forbidden by Eigen (see https://eigen.tuxfamily.org/dox/SparseBlock_8h_source.html).

提交回复
热议问题