Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen 3 - Slicing a MatrixXd to reverse the columns order

Tags:

c++

r

rcpp

eigen3

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

like image 992
Marco Stamazza Avatar asked Mar 17 '23 21:03

Marco Stamazza


1 Answers

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

like image 52
Andrew Avatar answered Mar 19 '23 16:03

Andrew