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

Christos Hatzis christos at nuverabio.com
Sun May 6 17:42:37 CEST 2007

```Here is a recursive version of the same function:

"%^%" <- function(A, n) if(n == 1) A else A %*% (A %^% (n-1))

> a <- matrix(1:4, 2)

> a %^% 1
[,1] [,2]
[1,]    1    3
[2,]    2    4
> a %^% 2
[,1] [,2]
[1,]    7   15
[2,]   10   22
> a %^% 3
[,1] [,2]
[1,]   37   81
[2,]   54  118

-Christos

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Ron E.
> VanNimwegen
> Sent: Sunday, May 06, 2007 10:48 AM
> To: r-help at stat.math.ethz.ch; attenka at utu.fi
> Subject: Re: [R] A function for raising a matrix to a power?
>
> >  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
> ---
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

```

More information about the R-help mailing list