%mathpiper,def="MatrixPower"

//////
// power of a matrix (dr)
//////

MatrixPower(x_IsSquareMatrix, n_IsNonNegativeInteger) <--
[
   Local(result);
   result:=Identity(Length(x));
   While(n != 0)
   [
      If(IsOdd(n),
         result:=Dot(result,x));
      x:=Dot(x,x);
      n:=n>>1;
   ];
   result;
];

MatrixPower(x_IsSquareMatrix, n_IsNegativeInteger) <--
   MatrixPower(Inverse(x),-n);

%/mathpiper



%mathpiper_docs,name="MatrixPower",categories="User Functions;Linear Algebra"
*CMD MatrixPower --- get nth power of a square matrix
*STD
*CALL
	MatrixPower(mat,n)

*PARMS

{mat} -- a square matrix

{n} -- an integer

*DESC

{MatrixPower(mat,n)} returns the {n}th power of a square matrix {mat}. For
positive {n} it evaluates dot products of {mat} with itself. For negative
{n} the nth power of the inverse of {mat} is returned. For {n}=0 the identity
matrix is returned.

*E.G.
In> A:={{1,2},{3,4}}
Result: {{1,2},{3,4}};
In> MatrixPower(A,0)
Result: {{1,0},{0,1}};
In> MatrixPower(A,1)
Result: {{1,2},{3,4}};
In> MatrixPower(A,3)
Result: {{37,54},{81,118}};
In> MatrixPower(A,-3)
Result: {{-59/4,27/4},{81/8,-37/8}};

*SEE IsSquareMatrix, Inverse, Dot
%/mathpiper_docs