【问题标题】:Eigen - Concatenated matrix as a referenceEigen - 连接矩阵作为参考
【发布时间】:2016-11-19 00:45:12
【问题描述】:

以下代码将一个向量连接到一个矩阵:

using Eigen::VectorXd;
using Eigen::MatrixXd;

MatrixXd cbind1(const Eigen::Ref<const MatrixXd> X) {
  const unsigned int n = X.rows();
  MatrixXd Y(n, 1 + X.cols());
  Y << VectorXd::Ones(n), X;
  return Y;
}

该函数将 X 的内容复制到 Y。如何定义该函数以避免进行复制并返回对包含 VectorXd::Ones(n), X 的矩阵的引用?

谢谢。

【问题讨论】:

  • 这在我看来是不可能的。由于您不想将向量连接到 Original Matrix X,因此唯一的区别是深拷贝或浅拷贝,或类似的东西。
  • 我已经编辑了我对您的previous question 的回答,表明它们实际上是重复的。

标签: c++ eigen


【解决方案1】:

如果您已关注并阅读了 ggael 对您的 previous question 的回答(并且您似乎已经阅读了,因为您接受了他的回答),您就会阅读文档的 this page。通过稍微修改示例,您可以编写为MCVE 的一部分:

#include <iostream>
#include <Eigen/Core>

using namespace Eigen;

template<class ArgType>
struct ones_col_helper {
    typedef Matrix<typename ArgType::Scalar,
        ArgType::SizeAtCompileTime,
        ArgType::SizeAtCompileTime,
        ColMajor,
        ArgType::MaxSizeAtCompileTime,
        ArgType::MaxSizeAtCompileTime> MatrixType;
};

template<class ArgType>
class ones_col_functor
{
    const typename ArgType::Nested m_mat;

public:
    ones_col_functor(const ArgType& arg) : m_mat(arg) {};

    const typename ArgType::Scalar operator() (Index row, Index col) const {
        if (col == 0) return typename ArgType::Scalar(1);
        return m_mat(row, col - 1);
    }
};

template <class ArgType>
CwiseNullaryOp<ones_col_functor<ArgType>, typename ones_col_helper<ArgType>::MatrixType>
cbind1(const Eigen::MatrixBase<ArgType>& arg)
{
    typedef typename ones_col_helper<ArgType>::MatrixType MatrixType;
    return MatrixType::NullaryExpr(arg.rows(), arg.cols()+1, ones_col_functor<ArgType>(arg.derived()));
}

int main()
{
    MatrixXd mat(4, 4);
    mat << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;

    auto example = cbind1(mat);

    std::cout << example << std::endl;
    return 0;
}

【讨论】:

  • 我的编译器无法识别one_col_functor 中的Index 类型。它是Eigen 命名空间的一部分吗?
  • 是的,Eigen::Index
  • 它说在命名空间Eigen 中没有名为Index 的类型。通常不是Eigen::VectorXd::Index之类的吗?
  • 您使用的是 Eigen 3.3 吗?
  • 我正在使用 RcppEigen,它使用 Eigen 3.2.9。
猜你喜欢
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多