在Rcpp中将矩阵的第k行替换为零
Replacing the `k`-th row of a matrix with zero in Rcpp
我想询问使用临时变量来替换矩阵的第1行CCD_。
我想用零替换一行X
。
因此,我创建了一个名为Ynew1
的X
副本,在每次迭代中,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);
}
')
好的。我认为你试图实现的目标如下:
用零替换
k
1的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
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 如何用转义符替换字符串中的所有特殊字符
- 如何使用Rcpp将R函数转换为C++函数
- rcpp函数中的清理时间很长
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 在一个读写器队列中,我可以用volatile替换原子吗
- 用符号版本替换对函数的所有调用
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 替换基于地图的所有引用
- 按平均值替换数组中的元素
- 将 C++ 类与 Rcpp 一起使用,从 C 或 R 修改它
- 从 Rcpp Catch 测试中获取有关"inst/extdata"的数据
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 初始化 std::vector 替换为单大括号而不是双大括号
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- 删除/替换C++字符串中的多字符 (ÿû)
- 将 malloc 替换为数组
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 在Rcpp中将矩阵的第k行替换为零