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

ぐ巨炮叔叔 提交于 2019-12-08 21:52:43

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/13548253/eigen-library-return-a-matrix-block-in-a-function-as-lvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!