[R] A function for raising a matrix to a power?

Ron E. VanNimwegen vanron at ksu.edu
Sun May 6 16:48:09 CEST 2007


>  Hi,
>
> Is there a function for raising a matrix to a power? For example if 
> you like to compute A%*%A%*%A, is there an abbreviation similar to A3?
>
> Atte Tenkanen 
Hi Atte,

I was looking for a similar operator, because R uses scalar products 
when raising a matrix to a power with "^".  There might be something 
more elegant, but this little loop function will do what you need for a 
matrix "mat" raised to a power "pow":

mp <- function(mat,pow){
ans <- mat
for ( i in 1:(pow-1)){
ans <- mat%*%ans
}
return(ans)
}

Then, for your example:
> > A=rbind(c(1,1),c(-1,-2))
> > mp(A,3)
>      [,1] [,2]
> [1,]    1    2
> [2,]   -2   -5
Cheers,
Ron

---
Ron E. VanNimwegen
Ph.D. Candidate, Division of Biology (EEB)
Kansas Cooperative Fish & Wildlife Research Unit
205 Leasure Hall
Kansas State University
Manhattan, KS 66506-3501
vanron at ksu.edu
---



More information about the R-help mailing list