rcppreturns同矩阵

Rcpp returns the same matrix

我的 Rcpp 函数 returns 结果相同。在这个函数中,我更改了一些 studyClones 数字,但是当我获取结果时,我有相同的矩阵 studyClones。 我做错了什么?

Rcpp 代码:

  NumericMatrix myFunction(NumericMatrix study, NumericMatrix numMatrix, double coef){
  int ind = 0;
  int sizeImage = study.rows();
  NumericVector randomNumbers;
  for(int i=0; i<numMatrix.rows(); i++){
    for(int j=ind; j<(numMatrix(i,0)+ind); j++){
      randomNumbers = sample(sizeImage, ceil(numMatrix(i,0)*coef), false);
      for(int k=0; k<randomNumbers.length(); k++){
        if(study(randomNumbers[k],j)==1){
          study[randomNumbers[k],j] = 0;
        }else{
          study[randomNumbers[k],j] = 1;
        }
      }
    }
    ind += numMatrix(i,0);
  }
 return study;
}

R代码:

result <- myFunction(studyMatrix, numericMatrix, coefficienM)
all(result==studyMatrix)
[1] TRUE

你做错了什么,你错过了 study 是(大致)指向原始 R 数据的指针。当您在 C++ 级别修改 study 时,您修改的是原始矩阵而不是副本。因此,R 对象 studyMatrix 已就地修改,您也 return 它。所以基本上 resultstudyMatrix 都是在内存中修改的同一个原始对象。因此他们是平等的。

试试这段代码来理解:

void f(NumericMatrix M)
{
  M(0,0) = 0;
  return;
}

然后在 R

m = matrix(1, 2,2)
m
#>      [,1] [,2]
#> [1,]    1    1
#> [2,]    1    1
f(m)
m
#>      [,1] [,2]
#> [1,]    0    1
#> [2,]    1    1

要解决您的问题,您可以使用 clone

NumericMatrix f(NumericMatrix M)
{
  NumericMatrix MM = clone(M);
  MM(0,0) = 0;
  return MM;
}