@rayyamhk/matrix
Version:
A professional, comprehensive and high-performance library for you to manipulate matrices.
40 lines (31 loc) • 773 B
JavaScript
var _require = require('../../Error'),
INVALID_SQUARE_MATRIX = _require.INVALID_SQUARE_MATRIX;
/**
* Calculates the trace of any square Matrix,
* which is the sum of all entries on the main diagonal.<br><br>
*
* The trace is cached.
* @memberof Matrix
* @instance
* @returns {number} The trace of the square Matrix.
*/
function trace() {
var isSquare = this._isSquare !== undefined ? this._isSquare : this.isSquare();
if (!isSquare) {
throw new Error(INVALID_SQUARE_MATRIX);
}
if (this._trace !== undefined) {
return this._trace;
}
var A = this._matrix;
var size = A.length;
var tr = 0;
for (var i = 0; i < size; i++) {
tr += A[i][i];
}
this._trace = tr;
return tr;
}
;
module.exports = trace;
;