具有特征类型输出的特征二进制 Expr

Eigen binaryExpr with eigen type output

本文关键字:特征 二进制 Expr 类型 输出      更新时间:2023-10-16

我在尝试使用binaryExpr时遇到问题。这是我第一次使用它,所以我一直在关注 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);
       ^

如果你有一个解决方案可以使这项工作,这对我:)如果没有,我仍然会喜欢解释以了解正在发生的事情。多谢。

添加:

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

会做这项工作。这是因为隐式标量转换在 Eigen 中是明确不允许的,因此您必须明确表示两种不同的标量类型是兼容的。例如,不允许向VectorXf添加VectorXd

尽管如此,在我看来,你在这里滥用了艾根的特征。