[R] How to calculte the power of a matrix

William Dunlap wdunlap at tibco.com
Fri Dec 11 21:11:19 CET 2009


> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Moohwan Kim
> Sent: Friday, December 11, 2009 11:01 AM
> To: r-help at r-project.org
> Subject: [R] How to calculte the power of a matrix
> 
> Dear R family
> 
>  I have a following question.
>  Suppose I have a matrix as follows, for instance:
>  tau=
>  0 1 0 0 0
>  0 0 1 0 0
>  0 0 0 1 0
>  0 0 0 0 1
>  1 0 0 0 0
> 
>  I want to calculate (-m) power of tau, for example, m=893.
> 
> When I run tau^2, the outcome is just tau.

Are you looking for the matrix power analogous to matrix
multiplication, "%*%"?

The following does it for positive integer exponents, using
the "Russian peasant" method (at least that is what we called
it in school several decades ago).

> f <- function (mat, pow) 
{
    # mat %*% mat %*% mat %*% ... %*% mat, pow times
    ans <- diag(nrow(mat))
    while (pow > 0) {
        if (pow%%2) 
            ans <- ans %*% mat
        pow <- pow%/%2
        if (pow > 0) 
            mat <- mat %*% mat
    }
    ans
}
> tau <- 
structure(c(0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 
0, 0, 1, 1, 0, 0, 0, 0), .Dim = c(5L, 5L))
> f(tau,2)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    0
[2,]    0    0    0    0    1
[3,]    1    0    0    0    0
[4,]    0    1    0    0    0
[5,]    0    0    1    0    0

Call solve() on its output for negative exponents.
Matrix::expm() (matrix exponential) may be of use also.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> Any help would be appreciated.
> 
> thanks in advance.
> 
> best
> moohwan
> 
> ______________________________________________
> R-help at r-project.org 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