【问题标题】:How to obtain storage options from Eigen::MatrixBase<Derived>如何从 Eigen::MatrixBase<Derived> 获取存储选项
【发布时间】:2019-12-05 09:19:47
【问题描述】:

我正在编写模板函数,它应该将一些Eigen::MatrixBase&lt;Derived&gt; 作为输入,执行一些计算,然后返回新的特征值。我想以与输入相同的存储顺序返回值。

但我不知道如何从Eigen::MatrixBase&lt;Derived&gt; 获取存储订单。在这种情况下我能做什么,有可能吗?我知道我可以将存储顺序作为另一个模板参数传递,或者接收Eigen::Matrix&lt;InpScalar, InpStatRows, InpStatCols, InpStorageOrder&gt;,但如果可能的话,我想避免它

PS 对不起我的英语不好

【问题讨论】:

  • 你确定这就是你想要的吗? MatrixBase 用作 “任何矩阵、向量或表达式” (source) 的基类,因此特定于矩阵的存储顺序选项不适用
  • @kmdreko 我同意,这可能是个坏主意。顺便说一句,可以通过 .derived() 从 MatrixBase 获取数据指针。所以也许也可以提取存储顺序
  • @kmdreko 你知道如何在不指定所有模板参数的情况下声明接收一般特征矩阵的模板函数吗? (标量、行、列等)

标签: c++ templates eigen eigen3


【解决方案1】:

要查看MatrixBase&lt;Derived&gt;的存储顺序,可以查看IsRowMajor枚举:

int const StorageOrder = Derived::IsRowMajor ? Eigen::RowMajor : Eigen::ColMajor;

如果你想拥有与Derived相同存储顺序和相同大小的类型可以直接使用typename Derived::PlainObject(或PlainMatrix):

template<class Derived>
typename Derived::PlainObject foo(const Eigen::MatrixBase<Derived> & input)
{
   typename Derived::PlainObject return_value;
   // do some complicated calculations
   return return_value;
}

【讨论】:

    【解决方案2】:

    要回复您关于如何声明接收通用矩阵的函数的评论,您可以执行以下操作:

    由于函数(和方法)从它们的实际函数参数中推断出它们的模板参数,如下所示

    template <typename InpScalar, int InpStatRows, int InpStatCols, int InpStorageOrder>
    void foo(Eigen::Matrix<InpScalar, InpStatRows, InpStatCols, InpStorageOrder>& matrix)
    {
        //you can utilize InpStorageOrder here
    }
    

    matrix入参的模板参数会被自动推导出来,也就是说你在调用函数的时候不用显式指定,只要传入任意Eigen::Matrix就行了

    如何从另一个函数调用该函数的示例

    void bar()
    {
        Eigen::Matrix<double, 3, 3, Eigen::RowMajor> mat;
        foo(mat);
    }
    

    如果您只想获取给定矩阵的存储顺序,如果 Eigen 库中没有任何内容可以执行此操作,那么您可以为 Eigen 矩阵实现类型特征

    template <typename TMatrix>
    struct MatrixTraits {};
    
    //Partial specialization of MatrixTraits class template
    //will accept only `Eigen::Matrix` classes as its template argument
    template <typename InpScalar, int InpStatRows, int InpStatCols, int InpStorageOrder>
    struct MatrixTraits<Eigen::Matrix<InpScalar, InpStatRows, InpStatCols, InpStorageOrder>>
    {
        int StorageOrder = InpStorageOrder;
    };
    

    要利用它,你可以这样做:

    void bar()
    {
        Eigen::Matrix<double, 3, 3, Eigen::RowMajor> mat;
        int StorageOrder = MatrixTraits<decltype(mat)>::StorageOrder;
    }
    

    【讨论】:

    • Eigen::Matrix的第四个模板参数也包含对齐信息。而且你不需要自己实现这些特性来实现 OP 想要做的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多