c++ - 强制 Eigen 在运行时检查矩阵维度

标签 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 在运行时检查矩阵维度?这对于初学者和调试非常有用。

最佳答案

维度检查仅在 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

关于c++ - 强制 Eigen 在运行时检查矩阵维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327602/

相关文章:

c++ - "by the bytes"与 "in bytes"

c++ - 内存没有被释放,导致巨大的内存泄漏

c++ - Eigen 矩阵和 vector 之上的抽象类

c++ - 如何通过 solve() 跟踪 Eigen 对象?

c++ - 将图像绘制到透明位图时字符周围出现黑色边框

c++ - 无法推断模板参数

c++ - glTexSubImage 会导致黑色纹理,而 glTexImage 效果很好

c++ - 如何将 std::vector 转换为 Eigen 中的矩阵?

c++ - Eigen 矩阵 + Boost::Serialization/C++17

c++ - 特征值列加一