我正在尝试在 Rcpp 中编写顺序蒙特卡洛函数,但遇到以下问题:
我通过以下方式创建了一个 vector :
NumericVector R_t(Part*Ttau);
我只想填充 vector 的部分块。它应该是这样的:
for (int i=0;i<Part;i++){
R_t[i]=runif(1,0,2);
}
第二次我想拥有
for (int i=Part+1;i<2*Part;i++){
R_t[i]=runif(1,0,2);
}
但是好像不行。我可以在每次迭代中用新值替换旧值,但每次迭代都需要旧值。当我尝试编译时,出现以下错误:
cannot convert 'Rcpp::NUmericVector {aka Rcpp::Vector<14, Rcpp::PrserveStorage>}' to 'Rcpp::traits::storage_type<14>:: type {aka double}' in assignment
用具有 Part 和 Ttau 维度的二维矩阵替换 vector 会更容易吗?我想避免这最后一个选项。
很抱歉,如果这个问题已经得到解答,但我没有找到与此相近的 rcpp 内容
最佳答案
您正在尝试将长度为一的 vector 分配给需要 double
的位置,因此使用 [0]
访问第一个元素:runif (1,0,2)[0]
。但是,您也可以只用 Rcpp 糖结构替换循环,以避免一次重复生成一个随机值:
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector fill_vector(R_xlen_t n, R_xlen_t m) {
Rcpp::NumericVector res(n);
for (R_xlen_t i = 0; i < m; i++) {
res[i] = Rcpp::runif(1, 0, 2)[0];
}
return res;
}
// [[Rcpp::export]]
Rcpp::NumericVector fill_vector2(R_xlen_t n, R_xlen_t m) {
Rcpp::NumericVector res(n);
res[Rcpp::seq(0, m - 1)] = Rcpp::runif(m, 0, 2);
return res;
}
/***R
set.seed(123)
fill_vector(7, 4)
#[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000
set.seed(123)
fill_vector2(7, 4)
#[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000
set.seed(123)
c(runif(4, 0, 2), rep(0, 3))
#[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000
*/
关于c++ - 在 Rcpp 中用随机生成的值填充 vector 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37926624/