零步幅的奇怪特征图行为

Strange Eigen map behavior with zero stride

来自 Eigen::Stride 文档:

The inner stride is the pointer increment between two consecutive entries within a given row of a row-major matrix or within a given column of a column-major matrix.

The outer stride is the pointer increment between two consecutive rows of a row-major matrix or between two consecutive columns of a column-major matrix.

假设我想创建一个矩阵,其中包含作为一行的重复向量。在 python numpy 中,我可以使用零长度步幅来执行此操作。 Eigen 文档对零步幅只字不提,但行为看起来很奇怪:

typedef Matrix<float, Dynamic, Dynamic, RowMajor> MatrixType;

MatrixType M1(3, 3);
M1 << 1, 2, 3,
      4, 5, 6,
      7, 8, 9;

Map<MatrixType, 0, Stride<0, 0>> zeroMap(M1.data(), 2, 2);  
Map<MatrixType, 0, Stride<2, 0>> oneMap(M1.data(), 2, 2);  

cout << "Row stride = 0:" << "\n";
cout << zeroMap << "\n" << "Row stride = 2:" << "\n";
cout << oneMap;
cout << "\n";

Returns 两种情况的结果相同:

Row stride = 0:
1 2
3 4
Row stride = 2:
1 2
3 4

为什么步幅0和步幅2的结果一样?

编译时步幅为 0 在 Eigen 中表示 "natural stride"。如果你想多次重复一个向量,你应该使用.replicate()函数:

M1.row(0).replicate<3,1>();

另请查看 .rowwise().replicate().colwise().replicate(),每个都有模板参数或运行时参数(取决于您的实际需要)。