How to extract a subvector (of an Eigen::Vector) from a vector of indices in Eigen?

user1526533 picture user1526533 · Oct 9, 2014 · Viewed 10.2k times · Source

Suppose I have

Eigen::VectorXd x; //{1,2,3,4,5,6,7,8}

and

Eigen::VectorXd ind_vec; //{0,2,4,5}

Is there a way an easy way to extract the ind_vec elements of x?

Something like:

x.extract(ind_vec) returning {1, 3, 5, 6}

Answer

Javi picture Javi · Oct 9, 2015

Since the current answer was not satisfactory for me, I googled a bit and I found this tutorial in the Eigen documentation.

#include <Eigen/Dense>
#include <iostream>
using namespace std;
int main()
{
  Eigen::ArrayXf v(6);
  v << 1, 2, 3, 4, 5, 6;
  cout << "v.head(3) =" << endl << v.head(3) << endl << endl;
  cout << "v.tail<3>() = " << endl << v.tail<3>() << endl << endl;
  v.segment(1,4) *= 2;
  cout << "after 'v.segment(1,4) *= 2', v =" << endl << v << endl;
}

Will output:

v.head(3) =
1
2
3

v.tail<3>() = 
4
5
6

after 'v.segment(1,4) *= 2', v =
 1
 4
 6
 8
10
 6

I haven't tested it with vectors, but I guess should be possible as well.