用特征值求解最小二乘方程的正确方法是什么? [英] What is the correct way to solve a least square equation with eigen?
问题描述
我有以下简单的示例执行最小二乘,但出现以下断言错误。
I have the following simple example to perform a least square, but got the following assertion error.
断言失败:(i> = 0)&& ((((BlockRows == 1)&&
(BlockCols == XprType :: ColsAtCompileTime)&& i
Assertion failed: (i>=0) && ( ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && i
什么是正确的方法吗?
typedef Eigen::ArrayXd arr;
typedef Eigen::ArrayXXd arr2;
arr2 A(3, 3);
arr B(3);
A << 1, 0, 0, 0, 1, 0, 0, 0, 1;
B << 1, 2, 3;
auto x = A.matrix().colPivHouseholderQr().solve(B.matrix());
推荐答案
正如我的评论所述,问题在于 x
是一个抽象表达式,它存储对QR对象的引用,但是在最后一行之后,它将引用一个死对象,然后任何事情都可能发生!
As said in my comment, the problem is that x
is an abstract expression storing a reference to the QR object, but right after the last line it will reference a dead object and then anything can happen!
更确切地说, A.matrix()。colPivHouseholderQr()
创建一个临时对象,我们称其为 tmp_qr
。然后 tmp_qr.solve(B)
创建另一个对象,该对象变为 Solve<类型的
。该对象实际上存储了两个r参考:一个到 x
。 ..> tmp_qr
,另一个到 B
。在此行之后,临时对象 tmp_qr
被删除,因此 Solve< ...>
对象 x
有一个无效引用。就像引用已删除缓冲区的指针一样。最后,如果您稍后 x
,例如:
More precisely, A.matrix().colPivHouseholderQr()
creates a temporary object, let's call it tmp_qr
. Then tmp_qr.solve(B)
creates another object which becomes x
of type Solve<...>
. This object essentially stores two references: one to tmp_qr
, and one to B
. Right after this line, the temporary object tmp_qr
is deleted, so the Solve<...>
object x
has one dead reference. It is like a pointer referencing a deleted buffer. Finally, if you x
later, like:
VectorXd y = x;
operator =
将触发使用 x
引用的QR分解和 x <引用的右侧
B
/ code>也是,但是,等等... QR分解对象已被删除,因此充其量您会得到一个段错误。
operator=
will trigger the solve operation using the QR decomposition referenced by x
and the right-hand-side B
referenced by x
too, but, wait... the QR decomposition object has been deleted, so at best you'll get a segfault.
因此,解决方案是这样写的:
So the solution is to write:
VectorXd x = A.matrix().colPivHouseholderQr().solve(B.matrix());
请参阅Eigen的文档详细了解自动
如果您不知道得到什么,将很危险。
See Eigen's doc for more details on how auto
is dangerous if you don't know what you get.
这篇关于用特征值求解最小二乘方程的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!