简体   繁体   English

如何传递特征矩阵行参考,将其视为向量?

[英]How do I pass an Eigen matrix row reference, to be treated as a vector?

I have a function that operates on a Vector reference, eg 我有一个操作Vector引用的函数,例如

void auto_bias(const Eigen::VectorXf& v, Eigen:Ref<Eigen::VectorXf>> out)
{
  out = ...
}

and at some point I need to have this function operate on a Matrix row. 在某些时候我需要让这个功能在Matrix行上运行。 Now, because the default memory layout is column-major, I can't just Map<> the data the row points to into a vector. 现在,因为默认的内存布局是列主要的,所以我不能只将行指向的数据映射到矢量中。 So, how do I go about passing the row into the above function so that I can operate on it? 那么,我该如何将行传递给上面的函数以便我可以对它进行操作呢?

The not-so-pretty solution is to have a temp vector, eg 不那么漂亮的解决方案是有一个临时矢量,例如

VectorXf tmpVec = matrix.row(5);
auto_bias(otherVector, tmpVec);
matrix.row(5) = tmpVec;

but is there a way of doing it directly? 但有没有办法直接这样做?

You can modify your function to take a reference to the row type (which is a vector expression) instead of a vector. 您可以修改函数以引用行类型(它是向量表达式)而不是向量。 This is really only manageable with a template to infer that type for you: 这实际上只能通过模板来管理,以便为您推断出这种类型:

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

template<typename V>
void set_row(V&& v) {
   v = Eigen::Vector3f(4.0f, 5.0f, 6.0f);
}

int main() {
   Eigen::Matrix3f m = Eigen::Matrix3f::Identity();
   set_row(m.row(1));

   std::cout << m;
   return 0;
}

You can allow Ref<> to have a non default inner-stride (also called increment), as follows: 您可以允许Ref<>具有非默认的内部步幅(也称为增量),如下所示:

Ref<VectorXf, 0, InnerStride<>>

See the example function foo3 of the Ref's documentation . 请参阅Ref 文档的示例函数foo3

The downside is a possible loss of performance even when you are passing a true VectorXf . 缺点是即使传递真正的VectorXf也可能导致性能VectorXf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM