简体   繁体   English

从特征数组/矩阵的行中填充 std::vector

[英]Fill a std::vector from a row of an Eigen Array / Matrix

I have an Eigen Array2Xd and I want to put each of its rows into std::vector<double> .我有一个 Eigen Array2Xd ,我想将它的每一行放入std::vector<double>

The spline_knots is an Array2Xd of size (2, 4) with following values: spline_knots是一个大小为 (2, 4) 的 Array2Xd,具有以下值:

Array2Xd spline_knots(2, 4);
spline_knots << -1, 0, 30.57, 60.83,
                 0, 0, 9.73,  15.44;

I tried the following based on this answer :我根据这个答案尝试了以下方法:

vector<double> knot_xs(spline_knots.row(0).data(), 
                           spline_knots.row(0).data() + spline_knots.row(0).size());
vector<double> knot_ys(spline_knots.row(1).data(), 
                           spline_knots.row(1).data() + spline_knots.row(1).size());

However trying to copy each row into a vector with the above code I get the following result, which is very weird (first row begins with the correct elements, then zeros; second row has only zeros and ends with the third element of first row):但是尝试使用上面的代码将每一行复制到一个向量中,我得到以下结果,这很奇怪(第一行以正确的元素开始,然后是零;第二行只有零并以第一行的第三个元素结束) :

kont_xs:   -1   0   0   0 
knot_ys:    0   0   0   30.57

What is wrong here, and how can I create the vector from a row of the 2D array without a loop ?这里有什么问题,如何在没有循环的情况下从 2D 数组的一行创建向量?

Figured it out.弄清楚了。 The problem is related to storage order , the way how Eigen lays out a two dimensional array in memory.问题与 存储顺序有关,即 Eigen 如何在 memory 中布置二维数组的方式。 There are two possible layouts: RowMajor and ColumnMajor .有两种可能的布局: RowMajorColumnMajor The default layout is ColumnMajor , which stores the 2D array elements column-wise.默认布局是ColumnMajor ,它按列存储二维数组元素。

Knowing this, the weird result I get makes sense.知道这一点,我得到的奇怪结果是有道理的。 The .row(0).data() returns the pointer to the first element of the first row. .row(0).data()返回指向第一行第一个元素的指针。 The .row(0).size() is 4 and .row(0).data() + 4 takes the first 4 elements column-wise: [-1, 0, 0, 0] . .row(0).size()是 4 并且.row(0).data() + 4按列取前 4 个元素: [-1, 0, 0, 0] Same argument for the second column which starts at (1, 0) element, and counting 4 elements column-wise leads to [0, 0, 0, 30.57] .从 (1, 0) 元素开始的第二列的相同参数,并且按列计算 4 个元素导致[0, 0, 0, 30.57]

There are two solutions:有两种解决方案:

  • Make the Array/Matrix layout row-major :使 Array/Matrix 布局row-major
Array<double, 2, Dynamic, RowMajor> arr(2, 6);
arr << 1, 2, 3, 4
       5, 6, 7, 8;

vector<double> row1_vec(arr.row(0).data(), arr.row(0).data() + arr.cols());

// row1_vec:   1, 2, 3, 4

Array2Xd arr(2, 4);
arr << 1, 2, 3, 4, 
       5, 6, 7, 8;

vector<double> row1_vec(arr.cols());
Map<RowVectorXd>(&row1_vec[0], 1, arr.cols()) = arr.row(0);

// row1_vec:   1, 2, 3, 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM