Search code examples
c++eigeneigen3

Copy data from std::vector to Eigen's MatrixXd in C++


Eigen is a linear algebra library in C++. I have my data (double type) in a std::vector (DataVector in the code below) type array. I try to copy it row-wise using the following code which is still giving results column-wise.

Map<MatrixXd, RowMajor> MyMatrix(DataVector.data(), M, N);

Am I doing the correct syntax here?


Solution

  • No. The MatrixXd object has to be defined as row/column major. See the example below.

    #include <Eigen/Core>
    #include <iostream>
    #include <vector>
    
    using std::cout;
    using std::endl;
    
    int main(int argc, char *argv[])
    {
        std::vector<int> dat(4);
        int i = 0;
        dat[i] = i + 1; i++;
        dat[i] = i + 1; i++;
        dat[i] = i + 1; i++;
        dat[i] = i + 1;
        typedef Eigen::Matrix<int, -1, -1, Eigen::ColMajor> Cm;
        Eigen::Map<Cm> m1(dat.data(), 2, 2);
        cout << m1 << endl << endl;
    
        typedef Eigen::Matrix<int, -1, -1, Eigen::RowMajor> Rm;
        Eigen::Map<Rm> m2(dat.data(), 2, 2);
        cout << m2 << endl << endl;
    
        return 0;
    }
    

    Outputs:

    1 3
    2 4
    
    1 2
    3 4