在Rcpp中将矩阵的第k行替换为零

Replacing the `k`-th row of a matrix with zero in Rcpp

本文关键字:替换 Rcpp      更新时间:2023-10-16

我想询问使用临时变量来替换矩阵的第1行CCD_。

我想用零替换一行X

因此,我创建了一个名为Ynew1X副本,在每次迭代中,Ynew1的值都会被X(第一个值)更新。但是,在我的代码中,不仅Ynew1的行被0替换,X也被0替换。不幸的是,结果是Ynew1是矩阵全零(我原以为最后一行的结果是零值)。这是代码:

cppFunction('
            NumericMatrix cobo(NumericMatrix X){
            int n = X.nrow();
            NumericMatrix Ynew1(n,1);
            for (int k=0;k<n;k++){
              Ynew1 = X;
              for(int i=0;i<n;i++){
                    Ynew1(k,i)=0;
              }
            }
            return(Ynew1);
            }
            ')

好的。我认为你试图实现的目标如下:

用零替换k1的k

您正在使用的for循环结构并不理想。在每次i或行迭代中,您都要将x重新复制到Ynew,然后将行清零。

在这种情况下,您应该只针对k行,如下所示:

cppFunction('
// @param x A code{matrix} with dimensions n x m. 
// @param k An code{unsigned int} whose index begins at 1.
// @return A code{matrix} with row code{k} equal to zero.
Rcpp::NumericMatrix cobo(Rcpp::NumericMatrix x, unsigned int k){
  unsigned int n = x.nrow();
  // Bounds check
  if(k - 1 >= n){ stop("OOB Error"); }
  // Replace row by a vector of zeros.
  x(k - 1, Rcpp::_) = Rcpp::NumericVector(x.ncol());
  return x;
}
')

注:该函数处理R矩阵输入。(例如,假设索引从1开始,而不是C++的0。)

示例:

set.seed(11) # Set seed for reproducibility
(x = matrix(rnorm(10),nrow = 5))
            [,1]        [,2]
[1,] -0.59103110 -0.93415132
[2,]  0.02659437  1.32360565
[3,] -1.51655310  0.62491779
[4,] -1.36265335 -0.04572296
[5,]  1.17848916 -1.00412058
cobo(x, 3)
            [,1]        [,2]
[1,] -0.59103110 -0.93415132
[2,]  0.02659437  1.32360565
[3,]  0.00000000  0.00000000
[4,] -1.36265335 -0.04572296
[5,]  1.17848916 -1.00412058