Eigen: replicate items along one dimension without useless allocations

前端 未结 1 1554
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 18:26

I have some vector vec and i want to obtain a new \"expression\" vec2 by copying values along dimension of vector

Eigen::VectorXf vec(5);
vec << 1, 2, 3, 4         


        
1条回答
  •  庸人自扰
    2021-01-22 19:22

    Using the devel branch you can use LinSpaced to generate the sequence of indices and then index the input vector:

    #include 
    #include 
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
      VectorXf vec(5);
      vec << 1, 2, 3, 4, 5;
      auto vecrep = vec(ArrayXi::LinSpaced(5*3,0,4));
      cout << vecrep.transpose() << endl;
    }
    

    you can then wrap the key line within a free function returning auto, in c++14:

    template
    auto magic_rep(const XprType &xpr, Index K) {
      return xpr(Eigen::ArrayXi::LinSpaced(xpr.size()*K,0,xpr.size()-1));
    }
    

    and in main:

    cout << magic_rep(vec,3).transpose() << endl;
    

    0 讨论(0)
提交回复
热议问题