%mathpiper,def="Trace"

//Retract("Trace",*);

Trace(matrix_IsList) <--
[
   Local(i,j,n,d,r,aux,result);
   
   d:=Dimensions(matrix);
   
   r:=Length(d); // tensor rank.
   
   n:=Minimum(d);    // minimal dim.
   
   result:=0;
   
   For(i:=1,i<=n,i++)
   [
      aux:=matrix[i];
      For(j:=2,j<=r,j++)
	 aux:=aux[i];
      result:=result+aux;
   ];
   result;
];

%/mathpiper

    %output,preserve="false"
      Result: True
.   %/output



%mathpiper_docs,name="Trace",categories="User Functions;Linear Algebra"
*CMD Trace --- trace of a matrix
*STD
*CALL
	Trace(M)

*PARMS

{M} -- a matrix

*DESC

{Trace} returns the trace of a matrix $M$ (defined as the sum of the
elements on the diagonal of the matrix).

*E.G.

In> A:=DiagonalMatrix(1 .. 4)
Result: {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};
In> Trace(A)
Result: 10;
%/mathpiper_docs