RCPP 函数,用于在 4 个方向上生成随机游走



我正在尝试生成一个名为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;
}

我尝试将 0 到 1 之间的随机数分配索引到 for 循环行中的列,以获得 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 次并计算到达端点的概率

谢谢

我会使用

#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;
}

最新更新