C++: Eigen conservativeResize too expensive?

后端 未结 1 535
-上瘾入骨i
-上瘾入骨i 2021-01-24 07:50

I have some Eigen Matrices whose dimensions I don\'t know in advance, I only have an upper bound. I have a loop in which I fill those matrices (I initialize them using the upper

1条回答
  •  深忆病人
    2021-01-24 08:36

    I think you could allocate large matrix once, then for multiplication use block create a view of its part which would contain meaningful data. You can reuse a big matrix then. This will spare you reallocations.

    Following example fully demonstrates it.

    ./eigen_block_multiply.cpp:

    #include 
    #include 
    using namespace std;
    using namespace Eigen;
    int main()
    {
      Matrix small;
      small << 1,2,3,
               4,5,6;
    
      Matrix big = Matrix::Constant(0.6);
      cout << "Big matrix:\n";
      cout << big << endl;
      cout << "Block of big matrix:\n";
      cout << big.block(0,0,3,2) << endl;
      cout << "Small matrix:\n";
      cout << small << endl;
      cout << "Product:\n";
      cout << small * big.block(0,0,3,2) << endl;
    
      Matrix small2;
      small2 << 1,2,3,
                4,5,6,
                7,8,9;
      big = Matrix::Constant(6.66);
      cout << "Product2:\n";
      cout << small * big.block(0,0,3,3) << endl;
    }
    

    Output:

    Big matrix:
    0.6 0.6 0.6 0.6
    0.6 0.6 0.6 0.6
    0.6 0.6 0.6 0.6
    0.6 0.6 0.6 0.6
    Block of big matrix:
    0.6 0.6
    0.6 0.6
    0.6 0.6
    Small matrix:
    1 2 3
    4 5 6
    Product:
    3.6 3.6
      9   9
    Product2:
    39.96 39.96 39.96
     99.9  99.9  99.9
    

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