c++ - 使用动态矩阵的 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
这可能吗,如果可以,我做错了什么?
解决方案
这是使用危险的地方之一auto
。
您链接到的示例具有:
Vector3f x = A.colPivHouseholderQr().solve(b);
^^^^^^^^
你有:
auto x = A.colPivHouseholderQr().solve(b);
^^^^^
在这种情况下,这是一个非常重要的区别,因为返回类型solve()
is not Vector3f
。它是一些中间无法表达的类型——我们正在构建一个表达式模板以供以后工作。但是该表达式模板保留了一堆中间引用,如果您不立即解决它们,它们就会悬空。
从特征文档:
简而言之:不要将
auto
关键字与 Eigen 表达式一起使用,除非您 100% 确定自己在做什么。特别是,不要使用 auto 关键字作为Matrix<>
类型的替代品。
推荐阅读
- reactjs - 获取未捕获的语法错误:提供 React 构建时出现意外的令牌“<”
- c++ - Qt Creator - “无法创建文件:未知错误”
- html - Flex 一个接一个地阻塞
- linux - “gcc 已散列(/bin/gcc)”是什么意思?
- javascript - 在传单中查找用户位置并将其设置在地图上
- android - 将图像和参数从 android(retrofit) 上传到 django 得到错误的请求
- javascript - 服务数据变化时自动刷新导航栏
- wpf - WPF:SizeChanged 总是被解雇
- metamodel - Apache 元模型已退役。备择方案?
- node.js - 与猫鼬聚集在一起