# [R] Exponentiate a matrix

Thu Sep 21 20:09:02 CEST 2006

```There is also mexp in the Matrix package and MatrixExp in the msm package.

Andreas

----- Original Message -----
From: "Dimitrios Rizopoulos" <Dimitris.Rizopoulos at med.kuleuven.be>
To: "Duncan Murdoch" <murdoch at stats.uwo.ca>
Cc: "Doran, Harold" <HDoran at air.org>; <r-help at stat.math.ethz.ch>
Sent: Thursday, September 21, 2006 4:26 PM
Subject: Re: [R] Exponentiate a matrix

>
> Quoting Duncan Murdoch <murdoch at stats.uwo.ca>:
>
>> On 9/21/2006 10:40 AM, Doran, Harold wrote:
>>> Suppose I have a square matrix P
>>>
>>> P <- matrix(c(.3,.7, .7, .3), ncol=2)
>>>
>>> I know that
>>>
>>>> P * P
>>>
>>> Returns the element by element product, whereas
>>>
>>>> P%*%P
>>>
>>> Returns the matrix product.
>>>
>>> Now, P^2 also returns the element by element product. But, is there a
>>> slick way to write
>>>
>>> P %*% P %*% P
>>>
>>> Obviously, P^3 does not return the result I expect.
>>
>>
>> I don't think there's anything built in, but it's easy to write your own:
>
> I think there was function mtx.exp() in the Malmig package, but it
> seems that this package has been withdrawn from CRAN. An old version
> appears to exist in:
>
> http://r.meteo.uni.wroc.pl/src/contrib/Descriptions/Malmig.html
>
> Best,
> Dimitris
>
>
>> "%^%" <- function(mat, pow) {
>>    stopifnot(length(pow) == 1, all.equal(pow, round(pow)), nrow(mat) ==
>> ncol(mat))
>>    pow <- round(pow)
>>    if (pow < 0) {
>>      mat <- solve(mat)
>>      pow <- abs(pow)
>>    }
>>    result <- diag(nrow(mat))
>>    while (pow > 0) {
>>      result <- result %*% mat
>>      pow <- pow - 1
>>    }
>>    result
>> }
>>
>> Now P %^% 3 will give you the matrix cube.
>>
>> Duncan Murdoch
>>
>> ______________________________________________
>> R-help at stat.math.ethz.ch mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>>
>
>
>
> Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help