1

I am trying to make a graph in R that plots probability of hitting the first state before the final state in a markov chain for different values of k. But when plotting if i only get the final value of k and not for all k for 1 to 17.

This is the question:

For p=0.5 and q=0.1, produce code to estimate the probability of hitting state 1 before the final state, for k=1,...,15. Produce a plot of the estimates against k. where k = dimension of transition

Can anyone spot my mistake?

for(k in 1:17)
{   p <- 0.5
    q <- 0.1
    P <- matrix (0, nrow = k, ncol = k, byrow = TRUE)
for (i in 1:k)
{   for (j in 1:k)
    {   if (i == 1 && i == j)
        {   P[i,j] <- 1
        }
        else if (i == k && i == j)
        {   P[i,j] <- 1
        }
        else if (i == j)
        {   P[i,j] <- p*(1-q)
        }
        else if (j == k && i != 1)
        {   P[i,j] <- q
        }   
        else if (i == j+1 && i != k)
        {   P[i,j] <- (1-p)*(1-q)
        }
    }
}
P

trials <- 1000
hits <- 0 #counter for no. of hits
for (i in 1:trials)
{   i <- 1 #no. of steps
    while(X[i] > 1 && X[i] < k)
    {   Y <- runif(1) #uniform samples
        p1 <- P[X[i],] #calculating the p-value
        p1 <- cumsum(p1)
        # changes in the chain
        if(Y <= p1[1])
          {   X[i+1] = 1}
        else if(Y <= p1[2])
          {   X[i+1] = 2}
        else if(Y <= p1[3])
          {   X[i+1] = 3}
        else if(Y <= p1[4])
          {   X[i+1] = 4}
        else if(Y <= p1[5])
          {   X[i+1] = 5}
        else if(Y <= p1[6])
          {   X[i+1] = 6}
        else if(Y <= p1[7])
          {   X[i+1] = 7}
        else if(Y <= p1[8])
          {   X[i+1] = 8}
        else if(Y <= p1[9])
          {   X[i+1] = 9}
        else if(Y <= p1[10])
          {   X[i+1] = 10}
        else if(Y <= p1[11])
          {   X[i+1] = 11}
        else if(Y <= p1[12])
          {   X[i+1] = 12}
        else if(Y <= p1[13])
          {   X[i+1] = 13}
        else if(Y <= p1[14])
          {   X[i+1] = 14}
        else if(Y <= p1[15])
          {   X[i+1] = 15}
        else if(Y <= p1[16])
          {   X[i+1] = 16}
        else if(Y <= p1[17])
          {   X[i+1] = 17}
        i <- i+1
    }
    if(X[i]==1)
    {   hits <- hits+1}
    else
    {   hits <- hits+0}
}
Probability <- hits/trials

}

Ahmed Jyad
  • 19
  • 3

1 Answers1

0

I think your primary mistake may be the statement

i <- 1 #no. of steps

in which you set the value of i to 1, even though you told it to loop over 1:trials in the preceding line.

Additionally, this code is incomplete because you use X[i] before you set X to anything, which causes an error.

Additionally, is there an error in the P matrix? I don't think your last row adds up to 1 -- you need to do a separate "else if" case for when i == k and j == k-1.

David Kaufman
  • 989
  • 1
  • 7
  • 20