首页 > 解决方案 > 使用动态矩阵的 Eigen 分解过程中的错误

问题描述

我正在尝试 Eigen here提供的示例,它似乎有效。但是,当我尝试更改矩阵类型以支持动态矩阵时,一切都会爆炸(下面的一切都与示例中的完全相同,但矩阵/向量的类型除外):

#include <Eigen/Dense>

#include <iostream>

using Matrix2D = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::AutoAlign>;
using Vector   = Eigen::Matrix<double, Eigen::Dynamic, 1>;

int main() {
   Matrix2D A(3,3);
   Vector b(3);

   A << 1,2,3,  4,5,6,  7,8,10;
   b << 3, 3, 4;

   std::cout << "Here is the matrix A:\n" << A << std::endl;
   std::cout << "Here is the vector b:\n" << b << std::endl;
   auto x = A.colPivHouseholderQr().solve(b);
   std::cout << "The solution is:\n" << x << std::endl;

    return 0;
}

运行期间的输出

Here is the matrix A:
 1  2  3
 4  5  6
 7  8 10
Here is the vector b:
3
3
4
The solution is:
a.out: eigen33/Eigen/src/Core/Block.h:123: Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>::Block(XprType&, Eigen::Index) [with XprType = Eigen::Matrix<double, -1, 1>; int BlockRows = 1; int BlockCols = 1; bool InnerPanel = false; Eigen::Index = long int]: Assertion `(i>=0) && ( ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && i<xpr.rows()) ||((BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) && i<xpr.cols()))' failed.
./makeEigen.sh: line 6: 12045 Aborted                 (core dumped) ./a.out

这可能吗,如果可以,我做错了什么?

标签: c++c++17eigeneigen3

解决方案


这是使用危险的地方之一auto

您链接到的示例具有:

Vector3f x = A.colPivHouseholderQr().solve(b);
^^^^^^^^

你有:

auto x = A.colPivHouseholderQr().solve(b);
^^^^^

在这种情况下,这是一个非常重要的区别,因为返回类型solve()is not Vector3f。它是一些中间无法表达的类型——我们正在构建一个表达式模板以供以后工作。但是该表达式模板保留了一堆中间引用,如果您不立即解决它们,它们就会悬空。

特征文档

简而言之:不要将auto关键字与 Eigen 表达式一起使用,除非您 100% 确定自己在做什么。特别是,不要使用 auto 关键字作为Matrix<>类型的替代品。


推荐阅读