Convert Eigen Matrix to C array

后端 未结 7 1943
深忆病人
深忆病人 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条回答
  •  情书的邮戳
    2020-11-30 04:00

    If the array is two-dimensional, one needs to pay attention to the storage order. By default, Eigen stores matrices in column-major order. However, a row-major order is needed for the direct conversion of an array into an Eigen matrix. If such conversions are performed frequently in the code, it might be helpful to use a corresponding typedef.

    using namespace Eigen;
    typedef Matrix RowMatrixXi;
    

    With such a definition one can obtain an Eigen matrix from an array in a simple and compact way, while preserving the order of the original array.

    From C array to Eigen::Matrix

    int nrow = 2, ncol = 3;
    int arr[nrow][ncol] =  { {1 ,2, 3},  {4, 5, 6} }; 
    Map eig(&arr[0][0], nrow, ncol);
    
    std::cout << "Eigen matrix:\n" << eig << std::endl;
    
    // Eigen matrix:
    // 1 2 3
    // 4 5 6
    

    In the opposite direction, the elements of an Eigen matrix can be transferred directly to a C-style array by using Map.

    From Eigen::Matrix to C array

    int arr2[nrow][ncol];
    Map(&arr2[0][0], nrow, ncol) = eig;
    
    std::cout << "C array:\n";
    for (int i = 0; i < nrow; ++i) {
      for (int j = 0; j < ncol; ++j) {
        std::cout << arr2[i][j] << " ";
      }
      std::cout << "\n";
    }
    
    // C array:
    // 1 2 3 
    // 4 5 6 
    

    Note that in this case the original matrix eig does not need to be stored in row-major layout. It is sufficient to specify the row-major order in Map.

提交回复
热议问题