Reputation: 8623
Suppose I have raw data, whose size I don't know at compile time, and that's why I need to store it in a dynamically sized matrix. I know I can initialise a static-sized matrix as follows:
std::vector<double> v {1.1, 2.2, 3.3, 4.4}; // "Raw data".
Eigen::Matrix<double, 2, 2> m(v.data());
std::cout << m << std::endl;
But is there a way of similarly initialising, or (even better) setting the data of a dynamic matrix? Something like the following (which doesn't compile)?
std::vector<double> v {1.1, 2.2, 3.3, 4.4}; // "Raw data".
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m(v.data(), 2, 2);
std::cout << m << std::endl;
I know from a comment in this post that I can just use Eigen::Map
, but as far as I understand, Eigen::Map
doesn't own the memory, so I can't, for example, return it from a function. I know that I can set the matrix element-wise but that feels so dumb LOL.
Upvotes: 0
Views: 706
Reputation: 13473
If you want to copy the raw data, assign the Map to a normal matrix.
std::vector<double> v {1.1, 2.2, 3.3, 4.4};
Eigen::MatrixXd m = Eigen::MatrixXd::Map(v.data(), 2, 2);
BTW: You don't need to deal with the template parameters such as Matrix<double, 2, 2>
or Matrix<double, Dynamic, Dynamic>
: There are type definitions for common cases. Just use Matrix2d
and MatrixXd
in your example. The type definitions are listed here for matrix and here for array
Upvotes: 3