2016-04-30 59 views
-2

我想問一下使用臨時變量來替換矩陣的第k行。在Rcpp中用零替換矩陣的第k行

我想將一行X替換爲零。

所以,我創建的X一份名爲Ynew1,並在每次迭代Ynew1值由X(第一個值)更新。但是,在我的代碼中,不僅Ynew1的行被替換爲0,而且還有X。不幸的是,結果是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); 
      } 
      ') 

回答

2

好的。我認爲你所要完成目標如下:

您所使用是不理想的零

的for循環結構取代xk個排。在每個i或行迭代中,您將重新複製xYnew,然後繼續將該行清零。

在這種情況下,你只應該針對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