Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen library: return a matrix block in a function as lvalue

I am trying to return a block of a matrix as an lvalue of a function. Let's say my function looks like this:

Block<Derived> getBlock(MatrixXd & m, int i, int j, int row, int column)
{
    return m.block(i,j,row,column);
}

As it turns out, it seems that C++ compiler understands that block() operator gives only temporary value and so returning it as an lvalue is prohibited by the compiler. However, in Eigen documentation there is some example that we can use Eigen as an lvalue (http://eigen.tuxfamily.org/dox/TutorialBlockOperations.html#TutorialBlockOperationsUsing) so I am wondering how we couldn't do the same with function return.

a.block(0,0,2,3) = a.block(2,1,2,3);

Thank you!

like image 204
HuaTham Avatar asked Nov 25 '12 04:11

HuaTham


1 Answers

I want to put what I found myself so it might be helpful to someone else:

My basic solution is to know what derived type you want the block to be. In this case:

Block<MatrixXd> getBlock(MatrixXd & m, int i, int j, int row, int column)
{
    return m.block(i,j,row,column);
}

It is interesting to me to notice that this method will return the reference to the content of matrix m by default. So if we do:

MatrixXd m = MatrixXd::Zero(10,10);
Block<MatrixXd> myBlock = getBlock(m, 1, 1, 3, 3);
myBlock << 1, 0, 0, 
           0, 1, 0, 
           0, 0, 1;

The content in matrix m will be modified as well. Note that, however,

MatrixXd m = MatrixXd::Zero(10,10);
MatrixXd myBlock = getBlock(m, 1, 1, 3, 3);
myBlock << 1, 0, 0, 
           0, 1, 0, 
           0, 0, 1;

will not work. My understanding is that once we convert the block to another type Eigen makes a copy of the data before conversion.

like image 200
HuaTham Avatar answered Sep 17 '22 20:09

HuaTham