将数据从std :: vector复制到C ++中的Eigen的MatrixXd

时间:2022-09-01 16:35:46

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.

Eigen是C ++中的线性代数库。我在std :: vector(下面的代码中的DataVector)类型数组中有我的数据(double类型)。我尝试使用以下代码逐行复制它,该代码仍然按列提供结果。

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

Am I doing the correct syntax here?

我在这里做正确的语法吗?

1 个解决方案

#1


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

不可以。必须将MatrixXd对象定义为行/列主要对象。请参阅下面的示例。

#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

#1


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

不可以。必须将MatrixXd对象定义为行/列主要对象。请参阅下面的示例。

#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