动态矩阵特征分解过程中的误差

Error during decomposition with Eigen with dynamic matrices

本文关键字:过程中 误差 分解 特征 动态      更新时间:2023-10-16

我在这里尝试使用Eigen提供的示例,它似乎有效。然而,当我试图改变矩阵类型以支持动态矩阵时,一切都会爆炸(下面的一切与示例中完全一样,但针对矩阵/向量的类型(:

#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

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

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

您链接到的示例有:

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

您有:

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

在这种情况下,这是一个非常显著的区别,因为solve()的返回类型不是Vector3f。这是一种中间的无法表达的类型——我们正在构建一个表达式模板,以便稍后进行工作。但该表达式模板保留了一堆中间引用,如果您不立即解析它们,这些引用就会挂起。

来自Eigen文档:

简而言之:不要在Eigen的表达式中使用auto关键字,除非你100%确定自己在做什么。特别是,不要使用auto关键字来替换Matrix<>类型。