Friday, 3 June 2016

Matrix multiplication in R

It's quite easy to multiply matrices in R. For example if you have a row matrix:
> a <- matrix(c(0,0,0.5,0.5),1,4)
> a
     [,1] [,2] [,3] [,4]
[1,]    0    0  0.5  0.5

and a 4x4 square matrix:
> P <- matrix(c(0,1/3,1/3,0,1/3,0,0,1,1/3,0,0,0,1/3,2/3,2/3,0),4,4)
> P
          [,1]      [,2]      [,3]      [,4]
[1,] 0.0000000 0.3333333 0.3333333 0.3333333
[2,] 0.3333333 0.0000000 0.0000000 0.6666667
[3,] 0.3333333 0.0000000 0.0000000 0.6666667
[4,] 0.0000000 1.0000000 0.0000000 0.0000000


Now multiply them:
> a %*% P
          [,1] [,2] [,3]      [,4]
[1,] 0.1666667  0.5    0 0.3333333


Handy for Markov chains!



No comments:

Post a Comment