本特征将矩阵行/列与向量L值参考结合
如何将矩阵的列(或行)传递给函数作为L值矢量参考? 这是动态分配矩阵的一个示例:
#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;
}
f2
f1
触发汇编错误,类型::
错误:无法绑定类型的非const lvalue参考 'eigen :: vectorxd&' {aka'eigen :: matrix< double,-1,1>&'} to rvalue 类型的'eigen :: vectorxd'{aka'eigen :: matrix< double,-1,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;
}
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:
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>’}
I face the same issue with compile-time sized matrices, e.g.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是eigen :: ref是设计用于。
请注意,仅在内部维度沿线的元素是连续的,可突变的参考才能起作用。因此,它可以与列矩阵的单列一起使用(默认值),但不能行。对于行矩阵,这是反之亦然。
const refs(
const eigen :: ref&lt; const eigen :: vectorxd&gt;&amp;
在这些情况下确实有效,但它们创建了临时副本。This is what Eigen::Ref is designed to do.
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.