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

匆匆过客 提交于 2021-02-07 18:38:17

问题


I have a function that operates on a Vector reference, e.g.

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. 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, e.g.

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

but is there a way of doing it directly?


回答1:


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;
}



回答2:


You can allow Ref<> to have a non default inner-stride (also called increment), as follows:

Ref<VectorXf, 0, InnerStride<>>

See the example function foo3 of the Ref's documentation.

The downside is a possible loss of performance even when you are passing a true VectorXf.



来源:https://stackoverflow.com/questions/32144223/how-do-i-pass-an-eigen-matrix-row-reference-to-be-treated-as-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!