Convert Eigen Matrix to C array

后端 未结 7 1942
深忆病人
深忆病人 2020-11-30 03:33

The Eigen library can map existing memory into Eigen matrices.

float array[3];
Map(array, 3).fill(10);
int data[4] = 1, 2, 3, 4;
Matrix2i mat         


        
7条回答
  •  旧时难觅i
    2020-11-30 04:14

    The solution with Map above segfaults when I try it (see comment above).

    Instead, here's a solution that works for me, copying the data into a std::vector from an Eigen::Matrix. I pre-allocate space in the vector to store the result of the Map/copy.

    Eigen::MatrixXf m(2, 2);
    m(0, 0) = 3;
    m(1, 0) = 2.5;
    m(0, 1) = -1;
    m(1, 1) = 0;
    
    cout << m << "\n";
    
    // Output:
    //    3  -1
    // 2.5   0
    
    // Segfaults with this code: 
    //
    // float* p = nullptr;
    // Eigen::Map(p, m.rows(), m.cols()) = m;
    
    // Better code, which also copies into a std::vector:
    
    // Note that I initialize vec with the matrix size to begin with:
    std::vector vec(m.size());
    Eigen::Map(vec.data(), m.rows(), m.cols()) = m;
    
    for (const auto& x : vec)
      cout << x << ", ";
    cout << "\n";
    
    // Output: 3, 2.5, -1, 0
    

提交回复
热议问题