强制Eigen在运行时检查矩阵尺寸

时间:2019-03-24 19:21:38

标签: c++ eigen

似乎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在运行时检查矩阵尺寸?这对于初学者和调试真的很有用。

1 个答案:

答案 0 :(得分:3)

仅当未定义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
相关问题