I want to retrieve certain elements in an Eigen array and return them as a vector. I use the following code:
Eigen::ArrayXXi test;
test.resize(5,5);
test.setRandom();
Eigen::Matrix<int, 2, 3> inds;
inds<<0, 2, 3, 2, 3, 1;
auto res = test(inds.row(0), inds.row(1));
std::cout<<"test: \n"<<test <<std::endl;
std::cout<<"inds: \n"<<inds <<std::endl;
std::cout<<"res: \n"<<res <<std::endl;
The output is:
test:
730547559 -649503489 -48539462 893772102 -1038736613
-226810938 -353856438 276748203 291438716 -552146456
607950953 576018668 -290373134 466641602 -779039257
640895091 -477225175 28778235 -769652652 653214605
884005969 115899597 971155939 229713912 -737276042
inds:
0 2 3
2 3 1
res:
-48539462 893772102 -649503489
-290373134 466641602 576018668
28778235 -769652652 -477225175
The result is a matrix. I note that the diagonal of the matrix is the result I want. I could use res.diagonal() to retrieve the vector. However, I am still wondering if I can do the same thing in a more efficient way.
You can reshape the
testArray to a column and then use the single-index access operator:Generally, be careful when using
autowith Eigen expressions (this case is fine, as long astestandindsare still valid whenresis used).