在 Rcpp 中用零替换矩阵的第 k 行
Replacing the `k`-th row of a matrix with zero in Rcpp
我想问一下用临时变量替换矩阵的第k
行。
我想用零替换一行 X
。
因此,我创建了一个名为 Ynew1
的 X
副本,并且在每次迭代中 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);
}
')
好的。我认为 objective 您要完成的是以下内容:
replace the k
-th row of x
by zero
您使用的 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
我想问一下用临时变量替换矩阵的第k
行。
我想用零替换一行 X
。
因此,我创建了一个名为 Ynew1
的 X
副本,并且在每次迭代中 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);
}
')
好的。我认为 objective 您要完成的是以下内容:
replace the
k
-th row ofx
by zero
您使用的 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