【问题标题】:Eigen binaryExpr with eigen type output具有特征类型输出的特征 binaryExpr
【发布时间】:2017-10-25 19:46:39
【问题描述】:

我在尝试使用 binaryExpr 时遇到问题。这是我第一次使用它,所以我一直关注Eigen documentation

为了我的使用,我需要一个具有 Eigen 类型输入和输出的函子,但这不想编译,我不明白为什么。我查看了代码中的解释,但我认为这不适用于这里,因为我使用浮点数和浮点数数组

// We require Lhs and Rhs to have "compatible" scalar types.
// It is tempting to always allow mixing different types but remember that this is often impossible in the vectorized paths.
// So allowing mixing different types gives very unexpected errors when enabling vectorization, when the user tries to
// add together a float matrix and a double matrix.

这是我需要的一个简短的使用示例,它会导致我遇到相同的编译错误:

#include <eigen3/Eigen/Dense>

using namespace std;
using namespace Eigen;

struct myBinaryFunctor {
  EIGEN_EMPTY_STRUCT_CTOR(myBinaryFunctor)
  typedef Vector2f result_type;
  Vector2f operator()(const Matrix<float,9,1>& a,const float& f) const
  {
      float x = a.head(4).sum()*f;
      float y = a.tail(5).sum()/f;
      return Vector2f(x,y);
  }
};

int main()
{
    constexpr int n = 3;
    Matrix<Matrix<float,9,1>,n,n> Ma;
    Matrix<float,n,n> F;
    Matrix<Vector2f,n,n> R;

    for(size_t i = 0, sizeMa = Ma.size(); i<sizeMa; i++)
    {
        Ma(i).setOnes();
    }

    F.setConstant(n,n,2);

    R = Ma.binaryExpr(F,myBinaryFunctor());

    return 0;
}

编译输出为:

/usr/local/include/eigen3/Eigen/src/Core/CwiseBinaryOp.h:107: erreur : static assertion failed: YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY
       EIGEN_CHECK_BINARY_COMPATIBILIY(BinaryOp,typename Lhs::Scalar,typename Rhs::Scalar);
       ^

如果您有一个可以完成这项工作的解决方案,这对我来说将是一个巨大的帮助:) 如果没有,我仍然会喜欢解释以了解正在发生的事情。非常感谢。

【问题讨论】:

    标签: c++ eigen


    【解决方案1】:

    添加:

    namespace Eigen {
    template<>
    struct ScalarBinaryOpTraits<Matrix<float,9,1>,float,myBinaryFunctor> {
      typedef Vector2f ReturnType;
    };
    }
    

    将完成这项工作。这是因为在 Eigen 中明确禁止隐式标量转换,因此您必须明确说明两种不同的标量类型是兼容的。例如,不允许将 VectorXd 添加到 VectorXf

    不过,在我看来,你在这里滥用了 Eigen 的功能。

    【讨论】:

    • 感谢您的回答,我从未想过明确告诉 Eigen 允许此操作。不过,我不确定您所说的“滥用 Eigen 的功能”是什么意思。使用一元和二元 Expr 似乎是做我想做的最明确的方式。对我来说,它看起来比原始循环要好得多,因为我不必考虑访问顺序,而且我可以给函子一个明确的名称。我不知道为什么,但它似乎也比原始循环更有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多