[英]eigen bind matrix row/column to vector l-value reference
如何將矩陣的列(或行)作為左值向量引用傳遞給函數? 這是動態分配矩陣的示例:
#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;
}
在f1
中對f2
的調用會觸發編譯錯誤,類型為:
錯誤:不能將'Eigen::VectorXd&'類型的非常量左值引用{aka'Eigen::Matrix<double, -1, 1>&'}綁定到'Eigen::VectorXd'類型的右值{aka'Eigen ::矩陣<double, -1, 1>'}
我在編譯時大小的矩陣中遇到了同樣的問題,例如
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;
}
這就是 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));
}
請注意,僅當沿內部維度的元素是連續的時,可變引用才有效。 因此它適用於列主矩陣的單列(默認),但不適用於一行。 對於行優先矩陣,反之亦然。
const refs ( const Eigen::Ref<const Eigen::VectorXd>&
) 在這些情況下確實有效,但它們會創建一個臨時副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.