Marco Stamazza Marco Stamazza - 2 months ago 15
C++ Question

Eigen 3 - Slicing a MatrixXd to reverse the columns order

I need to reverse the order of the columns of a MatrixXd using RcppEigen.

In

R
I would simply do

> M = matrix(1:9, ncol = 3)
> M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> M = M[, 3:1]
> M
[,1] [,2] [,3]
[1,] 7 4 1
[2,] 8 5 2
[3,] 9 6 3


In
C++
using Eigen I can do it with a loop

Eigen::MatrixXd m1(3, 3);
Eigen::MatrixXd m2(3, 3);
m1 << 1, 4, 7,
2, 5, 8,
3, 6, 9;

for (int i = 0; i < 3; i++){
m2.col(i) = m1.col(2 - i);
}

return m2;


Is there a better way of doing it? I looked also the
Eigen::Array
documentation but didn't find anything useful.

Thanks, Marco

Answer

Try m1.rowwise().reverse() Similarly use colwise() for row reversal.