Eigen block not lvalue?
Asked Answered
S

2

9

I am using Eigen library and its block operations, according to https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html the blocks are both lvalues and rvalues. But the following program does not compile:

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

int main() {
  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m(4, 4); 
  m << 1, 2, 3, 4,
       5, 6, 7, 8,
       9, 10, 11, 12, 
       13, 14, 15, 16; 
  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &column = m.col(0);
} 

In this program, I want to use column as a reference to the matrix m so I could alter the elements in-place. The error message is:

test_eigen_rvalue.cc: In function ‘int main()’:
test_eigen_rvalue.cc:11:73: error: invalid initialization of non-const reference of type ‘Eigen::Matrix<float, -1, -1>&’ from an rvalue of type ‘Eigen::DenseBase<Eigen::Matrix<float, -1, -1> >::ColXpr {aka Eigen::Block<Eigen::Matrix<float, -1, -1>, -1, 1, true>}’
   Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &column = m.col(0);

It seems the issue is that m.col(0) is not an lvalue.

Sensorium answered 4/10, 2016 at 19:38 Comment(2)
Did you check the return value of col? All you probably need to do is change your reference to a const reference.Belmonte
The linked page uses the words "rvalue" and "lvalue" incorrectly . m.col(0) is an rvalue, not an lvalue. The page is trying to say that you can write m.col(0) = whatever; to write to the column.Bernita
T
14

The block method does not return a Matrix object but a Block<> expression. In this case, it is a good idea to use the auto keyword (but be careful):

auto column = m.col(0);

Or use the convenient typedefs:

MatrixXf::ColXpr column = m.col(0);

Or even a Ref<>:

Ref<VectorXf> column = m.col(0);
Teter answered 4/10, 2016 at 21:17 Comment(1)
you're an eigen genius, I've found so many answers to my questions from you, :-DEmlynne
O
0

You can also try using block operations as shown here: https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html

For example: &column = m.block<4,1>(0,0);

Oler answered 4/10, 2016 at 20:2 Comment(1)
It gives the same error - I think m.block<4,1>(0,0) does exactly what m.col(0) does.Sensorium

© 2022 - 2024 — McMap. All rights reserved.