Eigen::Ref for concatenating matrices

前端 未结 2 1136
野性不改
野性不改 2020-12-10 21:45

If I want to concatenate two matrices A and B, I would do

using Eigen::MatrixXd;
const MatrixXd A(n, p);
const MatrixXd B(n, q);
Ma         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 22:20

    I'll add the C++14 version of @ggaels horizcat as an answer. The implementation is a bit sloppy in that it does not consider the Eigen compile-time constants, but in return it's only a two-liner:

    auto horizcat = [](auto expr1, auto expr2)
    {
        auto get = [expr1=std::move(expr1),expr2=std::move(expr2)](auto row, auto col)
                { return col::NullaryExpr(expr1.rows(), expr1.cols() + expr2.cols(), get);
    };
    
    int main()
    {
      Eigen::MatrixXd mat(3, 3);
      mat << 0, 1, 2, 3, 4, 5, 6, 7, 8;
    
      auto example1 = horizcat(mat,2*mat);
      std::cout << example1 << std::endl;
    
      auto example2 = horizcat(Eigen::MatrixXd::Identity(3,3), mat);
      std::cout << example2 << std::endl;
      return 0;
    }
    

    Note that the code is untested.

    That should be appropriate for most applications. However, in case you're using compile-time matrix dimensions and require maximum performance, prefer ggaels answer. In all other cases, also prefer ggaels answer, because he is the developer of Eigen :-)

提交回复
热议问题