逆数字矩阵按行

Reverse Numeric Matrix by Row

本文关键字:数字      更新时间:2023-10-16

使用Rcpp,对于我用R编写的包,我试图反转NumericMatrix,以便最后一行现在将成为第一行,第一行将成为最后一行,换句话说,相对行索引将从1, 2, 3, ... nn, n-1, n-2, .... 1

那么,如果我声明下面的函数:

NumericMatrix reverseByRow(NumericMatrix in){
  int r = in.nrow();
  NumericMatrix nw(r,in.ncol());
  for(int i = 0; i < r; i++){
    nw.row(i) = in.row(r-i-1);
  }
  return nw;
}

我有一个'N x M'的数字矩阵,称为'mid',我试图通过以下方式逐行反转:

        cout << "Reversing1: " << mid(0,0) << endl;
        cout << "Reversing2: "<< mid(1,0) << endl;
        mid = reverseByRow(mid); 
        cout << "Reversed1: " << mid(0,0) << endl;
        cout << "Reversed2: " << mid(1,0) << endl;

为什么我得到以下输出,暗示没有任何改变…??

Reversing1: 2806
Reversing2: 7
Reversed1: 2806
Reversed2: 7
我肯定错过了一些非常明显的东西…???

这是一个'固定'版本,有一个合适的变量名:

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix reverseByRow(NumericMatrix inmat) {
  int r = inmat.nrow();
  NumericMatrix nw(r,inmat.ncol());
  for(int i = 0; i < r; i++){
    nw.row(i) = inmat.row(r-i-1);
  }
  return nw;
}
/*** R
M <- matrix(1:9, 3, 3)
M
reverseByRow(M)
*/

按预期工作:

R> sourceCpp("/tmp/nicholas.cpp")
R> M <- matrix(1:9, 3, 3)
R> M
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
R> reverseByRow(M)
     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    2    5    8
[3,]    1    4    7
R>