将 Eigen::Matrix 的每一列转换为 std::vector?

Emi*_*773 2 c++ vector eigen

假设我有以下 Eigen::Matrix:

  Eigen::MatrixXf mat(3, 4);
  mat   <<  1.1, 2, 3, 50,
            2.2, 2, 3, 50,
            3.1, 2, 3, 50;
Run Code Online (Sandbox Code Playgroud)

现在如何将每一列转换为我std::vector<float> 尝试将此解决方案的改编,将 Eigen::VectorXd 类型转换为 std::vector

  std::vector<float> vec;
  vec.resize(mat.rows());
  for(int col=0; col<mat.cols(); col++){
     Eigen::MatrixXf::Map(&vec[0], mat.rows());
  }
Run Code Online (Sandbox Code Playgroud)

但这会引发以下错误:

n 模板:由于要求 'Map<Eigen::Matrix<float, -1, -1, 0, -1, -1>, 0, Eigen::Stride<0, 0>>::IsVectorAtCompileTime' , static_assert 失败YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX”

什么是正确且最有效的解决方案?

小智 5

我认为最优雅的解决方案是使用Eigen::Map. 在你的情况下,你会这样做:

 Eigen::MatrixXf mat(3, 4);
  mat   <<  1.1, 2, 3, 50,
            2.2, 2, 3, 50,
            3.1, 2, 3, 50;

  std::vector<float> vec;
  vec.resize(mat.rows());
  for(int col=0; col<mat.cols(); col++){
    Eigen::Map<Eigen::MatrixXf>(vec.data(), mat.rows(), 1 ) = mat.col(col); }
Run Code Online (Sandbox Code Playgroud)