Eigen how to concatenate matrix along a specific dimension?

前端 未结 3 1318
轻奢々
轻奢々 2020-12-05 02:20

I have two eigen matrices and I would like to concatenate them, like in matlab cat(0, A, B)

Is there anything equivalent in eigen?

Thanks.

3条回答
  •  长情又很酷
    2020-12-05 02:44

    I had a slightly different use case: To vertically stack a std::vector of Eigen matrices. Here is how I implemented a function which is more general purpose. Let me know if this can be further improved:

    // matrix_eig = Eigen::MatrixXf in RowMajor format
    matrix_eig VStack(const std::vector &mat_vec) {
      assert(!mat_vec.empty());
      long num_cols = mat_vec[0].cols();
      size_t num_rows = 0;
      for (size_t mat_idx = 0; mat_idx < mat_vec.size(); ++mat_idx) {
        assert(mat_vec[mat_idx].cols() == num_cols);
        num_rows += mat_vec[mat_idx].rows();
      }
      matrix_eig vstacked_mat(num_rows, num_cols);
      size_t row_offset = 0;
      for (size_t mat_idx = 0; mat_idx < mat_vec.size(); ++mat_idx) {
        long cur_rows = mat_vec[mat_idx].rows();
        vstacked_mat.middleRows(row_offset, cur_rows) = mat_vec[mat_idx];
        row_offset +=  cur_rows;
      }
      return vstacked_mat;
    }
    

提交回复
热议问题