Home > Software engineering >  How to roll the rows of a Eigen:Matrix?
How to roll the rows of a Eigen:Matrix?

Time:02-11

I want to reindex a Eigen:Matrix by rolling N∈ℤ rows like this (here N= 1):

1 4 7  ->  3 6 9
2 5 8      1 4 7
3 6 9      2 5 8 

Is there a simple way, or do I have to create a new matrix and copy over the data?

CodePudding user response:

I suggest setting up a new matrix and copying the data. Eigen's block operations allow doing this in an efficient way. Here is how a shift by n rows can be done for the example above.

MatrixXi A(3,3);
A << 1, 2, 3, 4, 5, 6, 7, 8, 9;
A.transposeInPlace();
int n = 1; // number of shifts
n = n % A.rows();

MatrixXi B(A.rows(), A.cols());
B.bottomRows(A.rows() - n) = A.topRows(A.rows() - n);
B.topRows(n) =  A.bottomRows(n);

std::cout << "B = " << B << std::endl;
  • Related