[英]eigen bind matrix row/column to vector l-value reference
How can i pass a column (or row) of a Matrix to a function as an l-value Vector reference?如何将矩阵的列(或行)作为左值向量引用传递给函数? Here is an example for dynamically allocated matrices:
这是动态分配矩阵的示例:
#include "eigen3/Eigen/Eigen"
void f2(Eigen::VectorXd &v) {
v(0) = 0e0;
}
void f1(Eigen::MatrixXd &m) {
if (m(0,0) == 0e0) {
// both calls below fail to compile
// f2(m.col(0)); // ERROR
// f2(m(Eigen::all, 0)); //ERROR
}
return;
}
int main() {
Eigen::MatrixXd m = Eigen::MatrixXd::Random(3,3);
f1(m);
return 0;
}
the call to f2
inside f1
triggers a compilation error, of type:在
f1
中对f2
的调用会触发编译错误,类型为:
error: cannot bind non-const lvalue reference of type 'Eigen::VectorXd&' {aka 'Eigen::Matrix<double, -1, 1>&'} to an rvalue of type 'Eigen::VectorXd' {aka 'Eigen::Matrix<double, -1, 1>'}
错误:不能将'Eigen::VectorXd&'类型的非常量左值引用{aka'Eigen::Matrix<double, -1, 1>&'}绑定到'Eigen::VectorXd'类型的右值{aka'Eigen ::矩阵<double, -1, 1>'}
I face the same issue with compile-time sized matrices, eg我在编译时大小的矩阵中遇到了同样的问题,例如
constexpr const int N = 3;
void f2(Eigen::Matrix<double,N,1> &v) {
v(0) = 0e0;
}
void f1(Eigen::Matrix<double,N,N> &m) {
if (m(0,0) == 0e0) {
// all calls below fail to compile
// f2(m.col(0)); ERROR
// f2(m(Eigen::all, 0)); ERROR
// f2(m.block<N,1>(0,0)); ERROR
}
return;
}
int main() {
Eigen::Matrix<double,N,N> m = Eigen::Matrix<double,N,N>::Random();
f1(m);
return 0;
}
This is what Eigen::Ref is designed to do .这就是 Eigen::Ref 的设计目的。
void f2(Eigen::Ref<Eigen::VectorXd> v) {
v[0] = 123.;
}
void f1(Eigen::Ref<Eigen::MatrixXd> m) {
m(1, 0) = 245.;
}
int main()
{
Eigen::MatrixXd m(10, 10);
f1(m);
f2(m.col(0));
assert(m(0,0) == 123.);
assert(m(1,0) == 245.);
// also works with parts of a matrix, or segments of a vector
f1(m.bottomRightCorner(4, 4));
}
Note that mutable references only work if elements along the inner dimension are consecutive.请注意,仅当沿内部维度的元素是连续的时,可变引用才有效。 So it works with a single column of a column-major matrix (the default) but not a row.
因此它适用于列主矩阵的单列(默认),但不适用于一行。 For row-major matrices it is vice-versa.
对于行优先矩阵,反之亦然。
const refs ( const Eigen::Ref<const Eigen::VectorXd>&
) do work in these cases but they create a temporary copy. const refs (
const Eigen::Ref<const Eigen::VectorXd>&
) 在这些情况下确实有效,但它们会创建一个临时副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.