Search code examples
c++eigen

Eigen taking a block of block


I have a large vector and I need to have access to it's parts as to separate vectors. For simplicity suppose that there is a vector A of length 10. Vector B is it's first five elements. Vector C is the first 3 elements of B. B and C share memory with A.

Eigen has several classes to handle such situation. Ref, Map and Block. Which one is the most natural way to handle the situation above? Also I'm specifically interested in case when B and C are created from A during their construction (to be able to build B and C inside member initialiser list of a class).

Seems that Block is the solution here. But Blocks can't be created from other Blocks...

#include "Eigen/Dense"

int main()
{
  Eigen::VectorXd a(10);
  Eigen::VectorBlock<Eigen::VectorXd> b(a, 0, 5);
  Eigen::VectorBlock<Eigen::VectorXd> c(b, 0, 3);
  return 0;
}

Produces:

error: no matching constructor for initialization of 'Eigen::VectorBlock<Eigen::VectorXd>' (aka
      'VectorBlock<Matrix<double, Dynamic, 1> >')
  Eigen::VectorBlock<Eigen::VectorXd> c(b, 0, 3);
                                      ^ ~~~~~~~

Solution

  • This is a rare case where auto is well suited for Eigen:

    auto b = a.segment(0,5);
    auto c = b.segment(0,3);
    

    The type of c will be nested Block, i.e., Block<Block<VectorXd,...>, ...>. In this case, Ref will work too:

    Ref<VectorXd> b = a.segment(0,5);
    Ref<VectorXd> c = b.segment(0,3);
    

    This might even be better because a Ref<VectorXd> is simpler to optimize for the compiler than a Block<Block<>>.