用于生成4个方向的随机游走的RCPP函数

时间:2018-08-21 13:39:42

标签: c++ r math rcpp

我正在尝试生成一个名为StepstoShop的函数,该函数将生成表示x和y坐标的n * 2矩阵。允许的方向只有北,南,东和西(不允许对角线移动)

这是我到目前为止开发的代码

#include <RcppArmadilloExtensions/sample.h>
#include <cstdlib>
#include <ctime>
using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]


NumericMatrix StepstoShop(double Steps){

    NumericMatrix SampleGen(Steps,2);
    int n=SampleGen.size();
    int colnum= rand()%1;



for( int i=0; i<n; i++)
      { SampleGen(i,colnum)=(rand()%3)-1;
      }

return SampleGen;
}

我已经尝试在通过行的for循环中的列中索引0到1之间的随机数分配,以获取4个方向的预期结果 (0,1)(1,0)(-1,0)(0,-1),但是我在8个方向上混合了。

任何指导,将不胜感激

谢谢

我追溯性地包含了R代码,以说明我正在尝试重新创建的内容

  # compute path
  n <- 1000
  rw <- matrix(0, ncol = 2, nrow = n)
  # generate the indices to set the deltas
  indx <- cbind(seq(n), sample(c(1, 2), n, TRUE))

  # now set the values
  rw[indx] <- sample(c(-1, 1), n, TRUE)
  # cumsum the columns
  rw[,1] <- cumsum(rw[, 1])
  rw[, 2] <- cumsum(rw[, 2])

  plot(0,type="n",xlab="x",ylab="y",main="Random Walk Simulation In Two 
  Dimensions",col=1:10,xlim=range(-10,15),ylim=range(-40,40))

  # use 'segments' to color each path
  segments(head(rw[, 1], -1)
  , head(rw[, 2], -1)
  , tail(rw[, 1], -1)
  , tail(rw[, 2], -1)
  , col = rainbow(nrow(rw) -1)  # a range of colors
  )

  end<-cbind(-10,30)
  start<-cbind(0,0)

  points(start,pch=16,col="green", cex = 3)
  points(end,pch=16,col="red", cex = 3)

想法是将该代码重复100,000次并计算到达端点的概率

谢谢

1 个答案:

答案 0 :(得分:1)

我会用

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerMatrix StepstoShop(double Steps){

  IntegerVector possible_x = IntegerVector::create(0, 1, -1, 0);
  IntegerVector possible_y = IntegerVector::create(1, 0, 0, -1);
  IntegerMatrix SampleGen(Steps, 2);
  int ind;

  for (int i = 0; i < Steps; i++) {
    ind = R::runif(0, 4);
    SampleGen(i, 0) = possible_x[ind];
    SampleGen(i, 1) = possible_y[ind];
  }

  return SampleGen;
}