繁体   English   中英

使用Rcpp中随机生成的值填充向量的一部分

[英]Fill a part of a vector with randomly generated values in Rcpp

我试图在Rcpp中编写一个Sequential Monte Carlo函数,我遇到了以下问题:

我通过以下方式创建了一个向量:

  NumericVector R_t(Part*Ttau);

我想填充矢量的部分块。 应该是这样的:

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的二维矩阵替换矢量会更容易吗? 我想避免这最后一个选择。

很抱歉,如果这已经得到解答,但我没有找到任何接近这个的rcpp

您正在尝试将长度为一的向量分配给需要double的位置,因此使用[0]访问第一个元素: runif(1,0,2)[0] 但是,您也可以使用Rcpp Sugar构造替换循环,以避免一次重复生成一个随机值:

#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

*/

RNG有两种选择:

  1. 使用Rcpp糖来匹配runif(n,a,b)通过Rcpp::runif(n,a,b) (返回NumericVector
  2. 通过每次从R::runif(a,b)绘制来创建自己的循环以模拟runif(n,a,b) R::runif(a,b)

@nrussell演示了如何通过Rcpp::runif(n,a,b)[0]对向量进行子集化来使用1,但省略了方法2。

以下是如何进行方法2:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector draw_vector(int n, int m) {
  Rcpp::NumericVector res(n);
  for (int i = 0; i < m; i++) {
    res[i] = R::runif(0.0, 2.0); // Draw a single element that is a double
  }
  return res;
}

/***R
set.seed(123)
draw_vector(7, 4)
*/

这给出了:

[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM