Skip to content
Browse files

Merge pull request #3 from jonnsl/master

Update the determinant method to be able to handle any sizes of matrices
  • Loading branch information...
2 parents ea49e24 + 3feefab commit af772fc153de927ec74747410d917d4ae6671df7 @arian committed Oct 8, 2011
Showing with 60 additions and 3 deletions.
  1. +3 −1 README.md
  2. +55 −2 Source/Array.Math.js
  3. +2 −0 Specs/spec/Array.Math.js
View
4 README.md
@@ -188,10 +188,12 @@ find the magnitude of the vector
### Array:determinant
-Find the determinant of a 2 by 2 matrix
+Find the determinant of a square matrix
#JS
[[4, 6], [3, 5]].determinant() // 2
+ [[5, 6, 4], [6, 3, 7], [5, 4, 2]].determinant() // 64
+ [[5, 3, 2, 2], [9, 5, 2, 9], [6, 8, 9, 4], [0, 6, 3, 4]].determinant() // -692
### Array:vectorLength
View
57 Source/Array.Math.js
@@ -38,6 +38,47 @@ provides:
...
*/
+(function(){
+
+function isSquare(matrix){
+ var n = matrix.count();
+ return matrix.every(function(line){
+ return line.count() == n;
+ });
+}
+
+function Sarrus(m){
+ return m[0][0] * m[1][1] * m[2][2] +
+ m[0][1] * m[1][2] * m[2][0] +
+ m[0][2] * m[1][0] * m[2][1] -
+ m[0][2] * m[1][1] * m[2][0] -
+ m[0][1] * m[1][0] * m[2][2] -
+ m[0][0] * m[1][2] * m[2][1];
+}
+
+function Laplace(matrix){
+ var det = 0,
+ l = matrix.length,
+ cache = copy(matrix, 1);
+
+ for (var i = 0; i < l; ++i){
+ det += Math.pow(-1, i+2) * matrix[i][0] * copy(cache).splice(i, 1).determinant();
+ }
+
+ return det;
+}
+
+/**
+ * Returns a two-level deep copy of an array.
+ */
+function copy(array, i)
+{
+ var copied = [];
+ array.each(function(line){
+ copied.push(line.slice(i));
+ });
+ return copied;
+}
Array.implement({
@@ -165,8 +206,18 @@ Array.implement({
},
determinant: function(){
- if (this.count() != 2) return 0; // only 2x2 matrices for now
- return this[0][0] * this[1][1] - this[0][1] * this[1][0];
+ if (!isSquare(this)) return 0; // only square matrices have determinants
+ switch (this.count())
+ {
+ case 1:
+ return this[0];
+ case 2:
+ return this[0][0] * this[1][1] - this[0][1] * this[1][0];
+ case 3:
+ return Sarrus(this);
+ default:
+ return Laplace(this);
+ }
},
vectorLength: function(){
@@ -192,3 +243,5 @@ Array.implement({
}
});
+
+})()
View
2 Specs/spec/Array.Math.js
@@ -198,6 +198,8 @@ describe('projection', function(){
describe('determinant', function(){
it('Calculate the determinant', function(){
expect([[4, 6], [3, 5]].determinant()).toBe(2);
+ expect([[5, 6, 4], [6, 3, 7], [5, 4, 2]].determinant()).toBe(64);
+ expect([[5, 3, 2, 2], [9, 5, 2, 9], [6, 8, 9, 4], [0, 6, 3, 4]].determinant()).toBe(692);
});
});

0 comments on commit af772fc

Please sign in to comment.
Something went wrong with that request. Please try again.