Search code examples
c++eigen

How to Convert Eigen Matrix to C/C++ Array


In Eigen C/C++ Library, how to converter the operation result (example below) from Eigen Matrix to C/C++ Array?

Example:

const Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>( array_C_input , 3, 3);

const Eigen::MatrixSquareRootReturnValue<Eigen::MatrixXf> result = m.sqrt();

float* array_C_output = (float*) result;   // Error: convert sqrt output to C array

Solution

  • If you want to compute the matrix root of a matrix passed as C-style array and handle the result like a C-style array, you can either store the result into a MatrixXf and use the data() member of that matrix:

    Eigen::MatrixXf matrix_root = Eigen::MatrixXf::Map( array_C_input , 3, 3).sqrt();
    float* array_C_output = matrix_root.data();
    

    Alternatively, if you already have memory allocated for the result, you can map the output to that:

    void foo(float* output_array, float const* input_array) {
      Eigen::MatrixXf::Map( output_array , 3, 3) = 
           Eigen::MatrixXf::Map( input_array , 3, 3).sqrt();
    }
    

    Note that Matrix::sqrt computes the matrix-root, i.e., if S = A.sqrt(), then S*S == M. If you want an element-wise root, you need to use

    Eigen::ArrayXXf::Map( input_array , 3, 3).sqrt()