Created
June 9, 2016 22:32
-
-
Save Swivelgames/ec2c4f962389bcbcb512dfde89629eeb to your computer and use it in GitHub Desktop.
Matrix 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Matrix; Matrix = (function(){ | |
var Constructor = function(inp) { | |
this.length = Matrix.getMatrixDims(inp); | |
if(!this.length) { | |
throw new Error("Invalid matrix"); | |
} | |
this.matrix = inp; | |
}; | |
Constructor.prototype = { | |
multiply: function(val) { | |
if(!val instanceof Matrix) { | |
throw new Error("Invalid matrix"); | |
return; | |
} | |
var product = [], | |
matrix = this.matrix, | |
matrix2 = val.matrix, | |
valDims = Matrix.getMatrixDims(matrix2); | |
if(!valDims) { | |
throw new Error("Invalid matrix"); | |
return; | |
} else if(valDims.x != this.length.y) { | |
throw new Error("Incompatible matrices"); | |
return; | |
} | |
for(var y=0;y<this.length.y;y++) { | |
product[y] = []; | |
for(var x=0;x<valDims.x;x++) { | |
product[y][x] = 0; | |
for(var i=0;i<this.length.x;i++) { | |
product[y][x] += matrix[y][i] * matrix2[i][x]; | |
} | |
} | |
} | |
return product; | |
} | |
}; | |
Constructor.getMatrixDims = function(mx) { | |
if(typeof mx !== "object" || !mx.length) return false; | |
var lens = { | |
y: mx.length, | |
x: mx[0].length | |
}; | |
for(var i=0;i<mx.length;mx++) { | |
if(mx[i].length !== lens.x) { | |
return false; | |
} | |
} | |
return lens; | |
}; | |
return Constructor; | |
})(); | |
module.exports = Matrix; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const util = require('util'); | |
const Matrix = require('./matrix.js'); | |
var Mx1 = new Matrix([ | |
[1,2,3], | |
[4,5,6] | |
]), | |
Mx2 = new Matrix([ | |
[1,2], | |
[3,4], | |
[5,6] | |
]); | |
var Product = Mx1.multiply(Mx2); | |
console.log( | |
util.inspect(Mx1, false, null) | |
); | |
console.log( | |
util.inspect(Mx2, false, null) | |
); | |
console.log( | |
util.inspect(Product, false, null) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: