Skip to content

Commit

Permalink
feat(det): add 2x2 and 3x3 determinants
Browse files Browse the repository at this point in the history
  • Loading branch information
zafarali authored and targos committed Nov 23, 2016
1 parent 8004999 commit 04ae195
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/abstractMatrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -1502,6 +1502,52 @@ function abstractMatrix(superCtor) {
selectionView(rowIndices, columnIndices) {
return new MatrixSelectionView(this, rowIndices, columnIndices);
}


/**
* Calculates and returns the determinant of a matrix as a Number
* @example
* new Matrix([[1,2,3], [4,5,6]]).det()
*
* @return {number}
*/

det(){
if(this.isSquare()){
if(this.columns === 2){
// 2 x 2 matrix
var a,b,c,d;
a = this.get(0, 0);
b = this.get(0, 1);
c = this.get(1, 0);
d = this.get(1, 1);

return a * d - ( b * c);

}else if(this.columns === 3){
// 3 x 3 matrix
var subMatrix0, subMatrix1, subMatrix2;
var a, b, c;

subMatrix0 = this.selection([1, 2], [1, 2]);
subMatrix1 = this.selection([1, 2], [0, 2]);
subMatrix2 = this.selection([1, 2], [0, 1]);
a = this.get(0, 0);
b = this.get(0, 1);
c = this.get(0, 2);

return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();

}else{
// general purpose determinant

throw Error('Not implemented yet');
}

}else{
throw Error('Determinant can only be calculated for a square matrix.');
}
}
}

Matrix.prototype.klass = 'Matrix';
Expand Down

0 comments on commit 04ae195

Please sign in to comment.