使用 Eigen 3 库的 .eval() 转置矩阵乘法中的段错误

Segfault in Tranposed matrix multiplication with .eval() with Eigen 3 library

为了以防万一,我添加了两个 .eval()。我没有遇到编译错误,也没有 运行 时间警告。只是段错误。

感谢您帮我解决这个问题。

测试:

#include <Eigen/Eigen>
#include <iostream>
using namespace Eigen;

int main() {
    Matrix<float, Dynamic, Dynamic> mat_b;
    Matrix<float, Dynamic, Dynamic> mat_c;

    mat_b << 1.0, 0.0, 0.5, 0.5,
             0.0, 1.0, 0.5, 0.5,
             1.0, 0.0, 1.0, 0.0,
             0.0, 1.0, 0.0, 1.0;

    mat_c << 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
             0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
             1.0, 0.0, 1.0, 0.0, 0.0, 0.0,
             1.0, 0.0, 0.0, 1.0, 0.0, 0.0;

    std::cout << (mat_b.transpose().eval() * mat_c).eval() << "\n";
}

结果:

Segmentation fault (core dumped)

documentatipon

所述

The comma initializer

Eigen offers a comma initializer syntax which allows the user to easily set all the coefficients of a matrix, vector or array. Simply list the coefficients, starting at the top-left corner and moving from left to right and from the top to the bottom. The size of the object needs to be specified beforehand. If you list too few or too many coefficients, Eigen will complain.

重点是我的。如果您期望 Matrix ctor 会从您的格式中推断出大小,那在 C++ 中根本不可能。看起来您创建了 16x1 和 24x1 矩阵,然后尝试将 1x16(转置第一个)乘以 24x1,这是不合法的。