为什么我不能在 Eigen3 中消除这个临时变量?
Why can't I eliminate this temporary variable in Eigen3?
我 运行 在矩阵向量乘法方面遇到了麻烦。也就是说,看起来无害的表达式总是 return 接近 [1 0] 的向量,而看起来相似的表达式 return 是正确的结果:
// version WITH temp var, correct
Eigen::Vector3d lcoord_eig(lcoord[0], lcoord[1], lcoord[2]);
auto lcoord2d = P3to2 * lcoord_eig;
std::cout << std::endl << lcoord2d << std::endl;
// version WITHOUT temp var, always [1 0]
auto lcoord2d_2 = P3to2 * Eigen::Vector3d(lcoord[0], lcoord[1], lcoord[2]);
std::cout << std::endl << lcoord2d_2 << std::endl;
其中 P3to2
是一个 2×3 矩阵 (Eigen::MatrixXd
),lcoord
是其他库的 3d 矢量类型,上面的代码包含在 for-循环。
一些输出(我的注释):
-0.0036135
2.1684e-18 // correct
1
0 // [1 0], wrong
0.00209583
0.000388139 // correct
1
5.55112e-17 // [1 0], wrong
0.00148429
-0.000435008 // correct
1
5.55112e-17 // [1 0], wrong
我花了很长时间才发现这个错误,我仍然不明白是什么原因导致第二个版本出现这样的行为。我犯了什么错误?
编辑:这也适用于常数向量,例如 Eigen::Vector3d(.5,.5,.5)
我的猜测(假设您没有在问题中包含足够的信息供任何人复制)是 auto
的使用是您的问题。在你的第二种情况下,非工作的情况下,我怀疑你留下了一个对被破坏的临时 Vector3D
.
的悬空引用
documentations 表示 "do not use the auto keywords with Eigen's expressions, unless you are 100% sure about what you are doing"。
如果您使用显式类型,您的程序将更清晰并且更有可能工作。
我 运行 在矩阵向量乘法方面遇到了麻烦。也就是说,看起来无害的表达式总是 return 接近 [1 0] 的向量,而看起来相似的表达式 return 是正确的结果:
// version WITH temp var, correct
Eigen::Vector3d lcoord_eig(lcoord[0], lcoord[1], lcoord[2]);
auto lcoord2d = P3to2 * lcoord_eig;
std::cout << std::endl << lcoord2d << std::endl;
// version WITHOUT temp var, always [1 0]
auto lcoord2d_2 = P3to2 * Eigen::Vector3d(lcoord[0], lcoord[1], lcoord[2]);
std::cout << std::endl << lcoord2d_2 << std::endl;
其中 P3to2
是一个 2×3 矩阵 (Eigen::MatrixXd
),lcoord
是其他库的 3d 矢量类型,上面的代码包含在 for-循环。
一些输出(我的注释):
-0.0036135
2.1684e-18 // correct
1
0 // [1 0], wrong
0.00209583
0.000388139 // correct
1
5.55112e-17 // [1 0], wrong
0.00148429
-0.000435008 // correct
1
5.55112e-17 // [1 0], wrong
我花了很长时间才发现这个错误,我仍然不明白是什么原因导致第二个版本出现这样的行为。我犯了什么错误?
编辑:这也适用于常数向量,例如 Eigen::Vector3d(.5,.5,.5)
我的猜测(假设您没有在问题中包含足够的信息供任何人复制)是 auto
的使用是您的问题。在你的第二种情况下,非工作的情况下,我怀疑你留下了一个对被破坏的临时 Vector3D
.
documentations 表示 "do not use the auto keywords with Eigen's expressions, unless you are 100% sure about what you are doing"。
如果您使用显式类型,您的程序将更清晰并且更有可能工作。