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
Try m1.rowwise().reverse()
Similarly use colwise()
for row reversal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With