Search code examples
c++eigen

Eigen multiple references/views of same data?


I would like to have two different Eigen containers point to the same data where one reference is a different view/subset of the data.

So something like this:

Eigen::VectorXd v1(3);
v1 << 1,2,3;

Eigen::VectorXd v1(2);
v2.data = &v1(0); //pseudo code 

v1(1) = 5;

cout << v2(1) << endl;

Where the value of v2(1) should now be 5.

Thanks in advance.


Solution

  • Found a possible solution:

    Eigen::VectorXd v1(3);
    v1 << 1,2,3;
    
    Eigen::Map<Eigen::VectorXd> v2(v1.head(0).data(),v1.size()-1);
    
    //v2 prints as { 1, 2 } 
    
    v1(1) = 9;
    
    //v2 now  prints as { 1, 9 }    
    

    Similiar question found here: Get matrix views/blocks from a Eigen::VectorXd without copying (shared memory)

    It seems I'll be able to use the new Map container in most of the ways you would a Vector so I think it'll be a suitable replacement.