Calculates the trace of a matrix.