简体   繁体   English

R中马尔可夫链的手动模拟(二)

[英]Manual simulation of Markov Chain in R (2)

Consider the Markov chain with state space S = {1, 2} , transition matrix考虑状态空间S = {1, 2}的马尔可夫链,转移矩阵

在此处输入图片说明

and initial distribution α = (1/2, 1/2) .和初始分布α = (1/2, 1/2)

  1. Simulate 5 steps of the Markov chain (that is, simulate X 0 , X 1 , . . . , X 5 ).模拟马尔可夫链的 5 个步骤(即模拟X 0 , X 1 , . . , X 5 )。 Repeat the simulation 100 times.重复模拟 100 次。

My solution:我的解决方案:

states <- c(1, 2)
alpha <- c(1, 1)/2
mat <- matrix(c(1/2, 1/2, 0, 1), nrow = 2, ncol = 2) 

nextX <- function(X, pMat)
{
    probVec <- vector()

    if(X == states[1])
    {
        probVec <- pMat[1,]
    }
    if(X==states[2])
    {
        probVec <- pMat[2,]
    }

    return(sample(states, 1, replace=TRUE, prob=probVec))
}

steps <- function(alpha1, mat1, n1)
{
    X0 <- sample(states, 1, replace=TRUE, prob=alpha1)

    if(n1 <=0)
    {
        return (X0)
    }
    else
    {
        vec <- vector(mode="numeric", length=n1)

        for (i in 1:n1) 
        {
            X <- nextX(X0, mat1)
            vec[i] <- X
        }

        return (vec)
    }
}

# steps(alpha1=alpha, mat1=mat, n1=5)

simulate <- function(alpha1, mat1, n1)
{
    for (i in 1:n1) 
    {
        vec <- steps(alpha1, mat1, 5)
        print(vec)
    }
}

simulate(alpha, mat, 100)

Output输出

> simulate(alpha, mat, 100)
[1] 1 2 2 2 2
[1] 2 1 2 2 2
[1] 1 1 1 1 1
[1] 1 1 1 1 1
[1] 2 2 2 2 2
[1] 2 1 1 2 2
[1] 1 1 1 1 1
[1] 2 2 1 2 2
[1] 1 1 1 1 1
[1] 2 2 1 1 2
[1] 2 2 1 2 2
[1] 1 1 1 1 1
[1] 1 1 1 1 1
[1] 1 1 2 2 2
[1] 1 1 1 1 1
[1] 2 1 2 2 2
[1] 1 1 1 1 1
[1] 1 1 1 1 1
[1] 2 1 2 1 1
[1] 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1 1 1 1
[1] 1 1 1 1 1
[1] 2 1 2 2 1
[1] 2 2 1 1 1
[1] 1 1 1 1 1
[1] 2 2 1 2 2
[1] 2 1 2 2 2
[1] 1 1 1 1 1

As you can see, I am getting same output in each iteration.如您所见,我在每次迭代中都得到相同的输出。

How can I fix my code?我该如何修复我的代码?

There are two issues:有两个问题:

Transposed Matrix转置矩阵

If you check the matrix you have input, it is the transpose of what you wanted:如果您检查输入的矩阵,它就是您想要的转置:

> mat
     [,1] [,2]
[1,]  0.5    0
[2,]  0.5    1

So, change that.所以,改变它。

States are not Chained状态不是连锁的

In the step function, the returned state is not used to initiate the subsequent state.step函数中,返回的状态不用于启动后续状态。 Instead, X0 just keeps getting passed in repeatedly:相反, X0只是不断地重复传入:

for (i in 1:n1) 
{
    X <- nextX(X0, mat1)
    vec[i] <- X
}

Honestly, you don't need X0 at all.老实说,您根本不需要X0 Just change all the X0 s in the step function to X and it should work.只需将step函数中的所有X0更改为X就可以了。

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

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