I want to use Eigen::Ref to have non-template functions using Eigen::Matrix arguments. My problem is that in these functions, I may have to resize the matrices referenced by the Eigen::Ref. I understand that for generality an Eigen::Ref should not be resized because it can map to an expression or a matrix block, but In my case, I am sure that what is behind my Eigen::Ref is an Eigen::Matrix.
To illustrate this:
#include "Eigen/Dense"
void add(Eigen::Ref<Eigen::MatrixXd> M, const Eigen::Ref<const Eigen::MatrixXd> &A, const Eigen::Ref<const Eigen::MatrixXd> &B) {
M=A+B;
}
int main() {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 32, 32> M(2,3);
Eigen::Matrix<double, 2, 2> A;
Eigen::Matrix<double, 2, 2> B;
add(M,A,B);
}
gives at runtime:
void Eigen::DenseBase<Derived>::resize(Eigen::Index, Eigen::Index) [with Derived = Eigen::Ref<Eigen::Matrix<double, -1, -1> >; Eigen::Index = long int]: Assertion `rows == this->rows() && cols == this->cols() && "DenseBase::resize() does not actually allow to resize."' failed.
I tried to cheat it:
void add(Eigen::Ref<Eigen::MatrixXd> M, const Eigen::Ref<const Eigen::MatrixXd> &A, const Eigen::Ref<const Eigen::MatrixXd> &B) {
Eigen::Ref<Eigen::Matrix<double,2,2>> MM(M);
MM=A+B;
}
but I got at runtime:
Eigen::internal::variable_if_dynamic<T, Value>::variable_if_dynamic(T) [with T = long int; int Value = 2]: Assertion `v == T(Value)' failed.
So, what could I do to handle this? In the Eigen documentation, the problem of resizing is addressed for template functions using MatrixBase as arguments, but for Eigen::Ref?
Eigen::MatrixXd
, why not passEigen::MatrixXd & M
? – chtz32
is not always the same, you could pass that as a template parameter. Otherwise, I don't see a safe way to implement this. – chtzMaxRowsAtCompileTime
andMaxColsAtCompileTime
ofM
inmain
will not be stored inside theRef
object. And the actual number of rows and cols will be copied into theRef
. So there is no way to safely resize theRef
object. Will theM
object always have a fixed maximum size at compile time? – chtz