让
trans_m
成为一个n乘n的一阶马尔可夫链的转移矩阵。在我的问题中,n很大,比如说是10,000,并且矩阵trans_m
是从Matrix
包构建的稀疏矩阵。否则,trans_m
的大小将会非常巨大。我的目标是给定一个初始状态向量s1
和这个转移矩阵trans_m
来模拟一系列马尔可夫链。考虑以下具体例子。 n <- 5000 # there are 5,000 states in this case.
trans_m <- Matrix(0, nr = n, nc = n, sparse = TRUE)
K <- 5 # the maximal number of states that could be reached.
for(i in 1:n){
states_reachable <- sample(1:n, size = K) # randomly pick K states that can be reached with equal probability.
trans_m[i, states_reachable] <- 1/K
}
s1 <- sample(1:n, size = 1000, replace = TRUE) # generate 1000 inital states
draw_next <- function(s) {
.s <- sample(1:n, size = 1, prob = trans_m[s, ]) # given the current state s, draw the next state .s
.s
}
sapply(s1, draw_next)
给定如上的初始状态向量s1
,我使用sapply(s1, draw_next)
来绘制下一个状态。当n
很大时,sapply
变得很慢。有更好的方法吗?
s1
的那行代码中加上了size=1000
...),然后只为每个状态生成下一个状态。但你不想为每个初始步骤生成一系列m
(m>2
)个状态,而只需要下一个状态,对吗? - Colonel Beauvel