typecasting Eigen::VectorXd to std::vector
Asked Answered
B

3

49

Their are many links to go the other way round but I am unable to find to get a std::vector from a Eigen::Matrix or Eigen::VectorXd in my specific case.

Barbershop answered 29/9, 2014 at 7:14 Comment(1)
Since I had a hard time finding the "many links to go the other way round", consider looking at https://mcmap.net/q/295052/-initialise-eigen-vector-with-std-vector for the other way around. I hope this saves some people some timeDote
M
64
vector<int> vec(mat.data(), mat.data() + mat.rows() * mat.cols());
Mistake answered 29/9, 2014 at 7:34 Comment(2)
mat.rows() * mat.cols() can be simplified to mat.size(), however, be aware that this solution only work for a plain Matrix<> object, while using a Map<> as in my answer works for sub-matrices too.Foresaid
If someone needs to copy a row of a matrix into a vector: vector<double> vec(arr.cols()); Map<RowVectorXd>(&vec[0], 1, mat.cols()) = mat.row(0);Suffragist
F
63

You cannot typecast, but you can easily copy the data:

VectorXd v1;
v1 = ...;
vector<double> v2;
v2.resize(v1.size());
VectorXd::Map(&v2[0], v1.size()) = v1;
Foresaid answered 29/9, 2014 at 7:35 Comment(1)
heyy thankyou for reply.. but i found the above answer more clean.Barbershop
F
2

You can do this from and to Eigen vector :

    //init a first vector
    std::vector<float> v1;
    v1.push_back(0.5);
    v1.push_back(1.5);
    v1.push_back(2.5);
    v1.push_back(3.5);

    //from v1 to an eignen vector
    float* ptr_data = &v1[0];
    Eigen::VectorXf v2 = Eigen::Map<Eigen::VectorXf, Eigen::Unaligned>(v1.data(), v1.size());

    //from the eigen vector to the std vector
    std::vector<float> v3(&v2[0], v2.data()+v2.cols()*v2.rows());


    //to check
    for(int i = 0; i < v1.size() ; i++){
        std::cout << std::to_string(v1[i]) << " | " << std::to_string(v2[i]) << " | " << std::to_string(v3[i]) << std::endl;
    }
Frankie answered 21/6, 2017 at 16:28 Comment(1)
v1.data() should be replaced by ptr_data, no?Henrietta

© 2022 - 2024 — McMap. All rights reserved.