c++eigen3yaml-cpp

Loading and Eigen Matrix from yaml using yaml-cpp


I'm using the very nice yaml-cpp project to read configurations into a C++ program. One of the config items stores an Eigen::Matrix<..> The following code works well but wondering if there is a better way?

main.cpp:

YAML::Node config = YAML::LoadFile("default.config");

const vector<double> eigenVec = config["my_matrix"].as<vector<double>>();

// https://eigen.tuxfamily.org/dox/group__TopicStorageOrders.html
Eigen::Matrix<double,4,4,Eigen::RowMajor> Matrix4x4(eigenVec.data());
cout << "Matrix  : " << Matrix4x4 << endl;

config.yaml:

my_matrix: [1.0, 2.0, 3.0, 4.0,
        0.0, 1.0, 3.0, 0.0,
        0.0, 7.0, 3.0, 0.0,
        3.0, 0.0, 3.0, 1.0 ]

Any guidance would be greatly appreciated.


Solution

  • maybe you can compressed into one line of the code

    Eigen::Matrix4d Matrix4x4= Eigen::Map<Eigen::Matrix<double, 4, 4, Eigen::RowMajor>>(config_node_["my_matrix"].as<std::vector<double>>().data());