Skip to content
Prev 33840 / 398513 Next

Markov chain simulation

On 25 Jun 2003 at 10:01, Philippe Hup? wrote:
For small transistion matrices (which seems to be what you ask for), 
something like this:
+               0.2, 0.1, 0.7), 3,3, byrow=TRUE)
+        n <- NROW(P)
+        result <- numeric(len)
+        result[1] <- 1
+        for (i in 2:len) {
+            result[i] <- sample(1:n, 1, prob=P[ result[i-1], ])
+        }
+        result
+ }
Note that this assumes the initial state to be 1, easy to modify wuth 
an extra argument to simMarkov.

Whe seeing a for-loop solution as above, it is natural to ask for a 
vectorized solution. But whith the FUNction within the loop using 
earlier results, that seems difficult.

Kjetil Halvorsen