簡體   English   中英

將 Eigen::Matrix 的每一列轉換為 std::vector?

[英]Convert every column of an Eigen::Matrix to an std::vector?

假設我有以下 Eigen::Matrix:

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

現在如何將每一列轉換為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());
  }

但這會引發以下錯誤:

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"

什么是正確和最有效的解決方案?

我認為最優雅的解決方案是使用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); }

下面的程序顯示了如何將 Eigen::Matrix 中的第一列提取到std::vector<float>

版本 1 :一次只提取一列

int main()
{
 

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

  std::vector<float> column1(mat.rows());

  
  for(int j = 0; j < mat.rows(); ++j)
  {
    column1.at(j) = mat(j, 0);//this will put all the elements in the first column of Eigen::Matrix into the column3 vector
  }
  for(float elem: column1)
  {
    std::cout<<elem<<std::endl;
  }

  //similarly you can create columns corresponding to other columns of the Matrix. Note that you can also 
  //create std::vector<std::vector<float>> for storing all the rows and columns as shown in version 2 of my answer
return 0;
}

版本 1 的輸出如下:

1.1
2.2
3.1

同樣,您可以提取其他列。

請注意,如果要提取所有列,則可以創建/使用std::vector<std::vector<float>> ,您可以在其中存儲所有行和列,如下所示:

版本 2 :將所有列提取到 2D std::vector

int main()
{
 

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

std::vector<std::vector<float>> vec_2d(mat.rows(), std::vector<float>(mat.cols(), 0));  

for(int col = 0; col < mat.cols(); ++col)
{
    for(int row = 0; row < mat.rows(); ++row)
    {
        
        vec_2d.at(row).at(col) = mat(row, col);
        
    }
    
}

//lets print out i.e., confirm if our vec_2d contains the columns correctly
for(int col = 0; col < mat.cols(); ++col)
{   std::cout<<"This is the "<<col+1<< " column"<<std::endl;
    for(int row = 0; row < mat.rows(); ++row)
    {
        
        std::cout<<vec_2d.at(row).at(col)<<std::endl;
        
    }   
}
  
return 0;
}

版本 2 的輸出如下:

This is the 1 column
1.1
2.2
3.1
This is the 2 column
2
2
2
This is the 3 column
3
3
3
This is the 4 column
50
50
50

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM