Reputation: 16193
I'm trying to learn the Eigen C++ library, and was wondering if there is some nice shorthand for initializing dynamic vectors and matrices. It would be really nice to write something like you would using a std::vector
std::vector<int> myVec = {1,2,3,6,5,4,6};
i.e.
VectorXi x = {1,2,3,4,7,5,7};
The closest (ugly) equivalent I can find involves Map
. .
int xc[] = {2,3,1,4,5};
Map<VectorXi> x(xc,sizeof(xc)/sizeof(xc[0]));
What other initialization methods are there?
Upvotes: 1
Views: 839
Reputation: 5854
For fixed size matrices/vectors, you can use the comma initializer:
Matrix3f m;
m<<1,2,3,4,5,6,7,8,9;
I can't test it right now, but it should work similarly for your situation:
VectorXi x(5);
x << 2,3,1,4,5;
If it does not, you could use a temporary Vector, fill it with the five elements using the comma initializer and then assign it to the VectorXi.
edit: You might also be interested in this page: Eigen: Advanced Initialization
Upvotes: 1
Reputation: 785
By the code you showed, you are OK in writing const items. So maybe you can do something like
std::vector<int> vec;
const int init_vec[5] = {1,2,3,4,5}
vec.assign(init_vec, init_vec + 5);
See this post of how use array to populate vectors.
EDIT: Correct a wrong link formating.
Upvotes: 1