trace method

double trace()

Calculates the trace of the Matrix.

Throws MatrixInvalidDimensions if the Matrix is not square.

final Matrix a = Matrix([ [ 1.0, 2.0, 3.0], [1.0,3.0,6.0], [0.0, 5.0, 1.0] ]);
print(a.trace());

prints

5.0

Implementation

double trace() {
  if (this.m != this.n) {
    throw MatrixInvalidDimensions();
  }
  double tr = 0.0;
  for (int i = 0; i < this.m; i++) {
    tr += this[i][i];
  }
  return tr;
}