Most programming languages have a built-in implementation of exponentiation for integers and reals only.



Task

Demonstrate how to implement matrix exponentiation as an operator.




#include once "matmult.bas"
#include once "rowech.bas"
#include once "matinv.bas"
 
operator ^ (byval M as Matrix, byval n as integer ) as Matrix
    dim as uinteger i, j, k = ubound( M.m, 1 )
    if n < 0 then return matinv(M) ^ (-n)
    if n = 0 then return M * matinv(M)
    return (M ^ (n-1)) * M
end operator
 
dim as Matrix M = Matrix(2,2), Q
dim as integer i, j, n
M.m(0,0) = 1./3 : M.m(0,1) = 2./3
M.m(1,0) = 2./7 : M.m(1,1) = 5./7
 
for n = -2 to 4
    Q = (M ^ n)
    for i = 0 to 1
        for j = 0 to 1
            print Q.m(i, j),
        next j
        print
    next i
    print
next n