强制 Eigen 在 运行 时间检查矩阵维度

Force Eigen to check matrices dimensions at run-time

Eigen 似乎不检查动态矩阵维度。例如,如果我执行以下代码:

auto EA = Eigen::MatrixXf(3, 2);
auto EB = Eigen::MatrixXf(3, 2);
for (auto i = 0; i < 3; ++i)
{
  for (auto j = 0; j < 2; ++j)
  {
    EA(i,j) = i + j + 1;
    EB(i,j) = i + j + 1;
  }
}
auto EC = EA*EB;
std::cout << "EA: " << std::endl << EA << std::endl;
std::cout << "EB: " << std::endl << EB << std::endl;
std::cout << "EC: " << std::endl << EC << std::endl;

它输出:

EA:
1 3
2 3
2 4
EB:
1 3
2 3
2 4
EC:
 7 12
 8 15
10 18

如何强制 Eigen 在 运行 时检查矩阵维数?这对初学者和调试非常有用。

尺寸检查仅在未定义 NDEBUG 宏时发生。这通常意味着调试版本。

没有 NDEBUG 的示例,其中检查成功中止程序:

g++ test.cpp -o test -I /usr/include/eigen3 && ./test
test: /usr/include/eigen3/Eigen/src/Core/ProductBase.h:102: Eigen::ProductBase<Derived, Lhs, Rhs>::ProductBase(const Lhs&, const Rhs&) [with Derived = Eigen::GeneralProduct<Eigen::Matrix<float, -1, -1>, Eigen::Matrix<float, -1, -1>, 5>; Lhs = Eigen::Matrix<float, -1, -1>; Rhs = Eigen::Matrix<float, -1, -1>]: Assertion `a_lhs.cols() == a_rhs.rows() && "invalid matrix product" && "if you wanted a coeff-wise or a dot product use the respective explicit functions"' failed.
Aborted (core dumped)

NDEBUG:

g++ test.cpp -o test -I /usr/include/eigen3 -DNDEBUG && ./test
EA: 
1 2
2 3
3 4
EB: 
1 2
2 3
3 4
EC: 
 5  8
 8 13
11 18