[R] How do I write a sum of matrixes??

David Winsemius dwinsemius at comcast.net
Tue May 6 14:55:58 CEST 2008


pascal vrolijk <pascalvrolijk at hotmail.com> wrote in
news:BAY120-W47837F2A708683682EB44AACD60 at phx.gbl: 

> Hello best helpers,
> 
> I am a new user and I have been struggling for hours. So finally I
> decide to ask you: If I have a matrix P, and P.2 = P%*%P, and
> P.3=P.2%*%P is there a function to calculate the power of a matrix??
> if not how can i do: for (i in 1:10)  {P.i=P^i} 

Three methods show up in a search "r-help power of a matrix":

1) Use a pre-built function:
library(msm)
?MatrixExp 

2) 
<https://stat.ethz.ch/pipermail/r-help/2007-May/131330.html>

3) Bill Venables offered this about a week ago in this list:
--------------
This is probably as good a way as any way for this kind of problem.
First define a binary operator:

> "%^%" <- function(x, n)
        with(eigen(x), vectors %*% (values^n * t(vectors)))

Your toy example then becomes

> m <- matrix(c(1, 0.4, 0.4, 1), nrow = 2)
> m
     [,1] [,2]
[1,]  1.0  0.4
[2,]  0.4  1.0

> m %^% (-0.5)
           [,1]       [,2]
[1,]  1.0680744 -0.2229201
[2,] -0.2229201  1.0680744 
-------------

-- 
David Winsemius


> after this I need to sum them up and my problem is to combine P and
> i to P.i  can anyone help me please??? 
> 
> Thanks and have a nice day, 
> 
> Pascal.



More information about the R-help mailing list