Skip to content

Commit 04ae195

Browse files
zafaralitargos
authored andcommitted
feat(det): add 2x2 and 3x3 determinants
1 parent 8004999 commit 04ae195

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/abstractMatrix.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1502,6 +1502,52 @@ function abstractMatrix(superCtor) {
15021502
selectionView(rowIndices, columnIndices) {
15031503
return new MatrixSelectionView(this, rowIndices, columnIndices);
15041504
}
1505+
1506+
1507+
/**
1508+
* Calculates and returns the determinant of a matrix as a Number
1509+
* @example
1510+
* new Matrix([[1,2,3], [4,5,6]]).det()
1511+
*
1512+
* @return {number}
1513+
*/
1514+
1515+
det(){
1516+
if(this.isSquare()){
1517+
if(this.columns === 2){
1518+
// 2 x 2 matrix
1519+
var a,b,c,d;
1520+
a = this.get(0, 0);
1521+
b = this.get(0, 1);
1522+
c = this.get(1, 0);
1523+
d = this.get(1, 1);
1524+
1525+
return a * d - ( b * c);
1526+
1527+
}else if(this.columns === 3){
1528+
// 3 x 3 matrix
1529+
var subMatrix0, subMatrix1, subMatrix2;
1530+
var a, b, c;
1531+
1532+
subMatrix0 = this.selection([1, 2], [1, 2]);
1533+
subMatrix1 = this.selection([1, 2], [0, 2]);
1534+
subMatrix2 = this.selection([1, 2], [0, 1]);
1535+
a = this.get(0, 0);
1536+
b = this.get(0, 1);
1537+
c = this.get(0, 2);
1538+
1539+
return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();
1540+
1541+
}else{
1542+
// general purpose determinant
1543+
1544+
throw Error('Not implemented yet');
1545+
}
1546+
1547+
}else{
1548+
throw Error('Determinant can only be calculated for a square matrix.');
1549+
}
1550+
}
15051551
}
15061552

15071553
Matrix.prototype.klass = 'Matrix';

0 commit comments

Comments
 (0)