Eigen library - references

Hello

I am using the Eigen library.

I have a 4x3 matrix of doubles and would like to obtain a reference to a row or column of the matrix (so that changes to the reference result in changes to the matrix).

I think the following code works with respect to a column:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include <iostream>
#include "Eigen/Dense"

using Eigen::MatrixXd;

int main()
{
    MatrixXd G(4,3); // global matrix

    G << 0.1, 0.2, 0.3,
         0.4, 0.5, 0.6,
         0.7, 0.8, 0.9,
         0.10,0.11,0.12;

    Eigen::Ref<Eigen::MatrixXd> A = G.col(1);

    A.row(2) << 0.99;

    std::cout << G;
}


which outputs:
1
2
3
4
 0.1  0.2  0.3
 0.4  0.5  0.6
 0.7 0.99  0.9
 0.1 0.11 0.12

However, when I want to get a reference to the row by changing the above to:
1
2
    Eigen::Ref<Eigen::MatrixXd> A = G.row(1);
    A.col(2) << 0.99;

I get the following error:
 
error: conversion from 'Eigen::DenseBase<Eigen::Matrix<double, -1, -1> >::RowXpr' {aka 'Eigen::Block<Eigen::Matrix<double, -1, -1>, 1, -1, false>'} to non-scalar type 'Eigen::Ref<Eigen::Matrix<double, -1, -1> >' requested

Thanks
Last edited on
Have you tried a normal reference?
Eigen::MatrixXd& A = G.col(1);
thanks

this gives the following error:

 
Non-const lvalue reference to type 'Eigen::MatrixXd' (aka 'Matrix<double, Dynamic, Dynamic>') cannot bind to a temporary of type 'Eigen::DenseBase<Eigen::Matrix<double, -1, -1>>::ColXpr' (aka 'Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, internal::traits<Matrix<double, -1, -1, 0, -1, -1>>::RowsAtCompileTime, 1, !IsRowMajor>')
I've taken a look at my local copy which I don't use btw, and there it says this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  /* You can access elements of vectors and matrices using normal subscripting:
  *
  * \code
  * Eigen::VectorXd v(10);
  * v[0] = 0.1;
  * v[1] = 0.2;
  * v(0) = 0.3;
  * v(1) = 0.4;
  *
  * Eigen::MatrixXi m(10, 10);
  * m(0, 1) = 1;
  * m(0, 2) = 2;
  * m(0, 3) = 3;
  * \endcode
  */


Therefore a reference should be to an element, not entire row or column.

Ref<> object can represent either a const expression or a l-value

https://eigen.tuxfamily.org/dox-devel/classEigen_1_1Ref.html
Seems like col() and row() do not return lvalue so Ref can't bind.

For single elements therefore it should not be needed to hold a Ref object but instead a plain reference to matrix ex:

1
2
3
4
5
6
7
MatrixXd G(4,3);
MatrixXd& ref = G;

ref(1,1) = 0;

// or
auto& MyRef = G(1,1);


Maybe someone skilled with the library can help more.
Last edited on
See the documentation about working with block matrices:
https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html
There are examples on that page.
Topic archived. No new replies allowed.