[R] better way to iterate matrix multiplication?
Jonathan Knibb
jonathan_knibb at hotmail.com
Tue Feb 1 15:04:50 CET 2011
I'm simulating a Markov process using a vector of proportions. Each
value in the vector represents the proportion of the population who are
in a particular state (so the vector sums to 1). I have a square matrix
of transition probabilities, and for each tick of the Markov clock the
vector is multiplied by the transition matrix.
To illustrate the sort of thing I mean:
pm <- c(0.5,0.5,0) # half of cases start in state 1, half in state 2
tm <- matrix(runif(9),nrow=3) # random transition matrix for illustration
tm <- t(apply(tm,1,function (x) x/sum(x))) # make its rows sum to 1
total.months = 10
for(month in 1:total.months) {pm <- pm %*% tm} # slow!
pm # now contains the proportion of cases in each state after 10 months
My question is: is there a quicker, more R-idiomatic way of doing it,
avoiding 'for'? I've been trying to use apply() to fill a matrix with
the vectors, but I can't get this to act iteratively.
Suggestions gratefully received!
More information about the R-help
mailing list