[R] Re: matrix __power__ (was "exponential")

Martin Maechler maechler at stat.math.ethz.ch
Thu Jan 22 18:22:27 CET 2004

>>>>> "Vicente" == Vicente Canto Casasola <vicented.canto.ext at juntadeandalucia.es>
>>>>>     on Thu, 22 Jan 2004 14:34:01 +0100 writes:

    Vicente> H i, all!  First of all, I'd like to apologize for
    Vicente> my poor English. It's for years I don't use it.

no problem at all.

    Vicente> This is a R-version of a function I wrote a long
    Vicente> ago for my HP48 calculator.  It works with the
    Vicente> binary expression of the power and just need to
    Vicente> duplicate the mem used by X.

excellent. This is really the way to solve the problem 
I think. 

As I've mentioned earlier in this thread,
computing a matrix "power" is really much easier than the
matrix exponential.

Hence I wouldn't use exponential in the function name.
Also note that trailing ";" are considered as `dirty' (they are
completely superfluous).

These slight modifications (+ initial "test") 

matPower <- function(X,n)
## Function to calculate the n-th power of a matrix X
    if(n != round(n)) {
        n <- round(n)
        warning("rounding exponent `n' to", n)
    phi <- diag(nrow = nrow(X))
    pot <- X # the first power of the matrix.

    while (n > 0)
        if (n %% 2)
            phi <- phi %*% pot

        n <- n %/% 2
        pot <- pot %*% pot


Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><

More information about the R-help mailing list