Skip to content

Instantly share code, notes, and snippets.

@Swivelgames
Created June 9, 2016 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swivelgames/ec2c4f962389bcbcb512dfde89629eeb to your computer and use it in GitHub Desktop.
Save Swivelgames/ec2c4f962389bcbcb512dfde89629eeb to your computer and use it in GitHub Desktop.
Matrix 2
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;
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)
);
@Swivelgames
Copy link
Author

Example output:

$ node test.js
{ length: { y: 3, x: 3 },
  matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] }
{ length: { y: 3, x: 3 },
  matrix: [ [ 2, 2, 2 ], [ 10, 10, 10 ], [ 20, 20, 20 ] ] }
[ [ 82, 82, 82 ], [ 178, 178, 178 ], [ 274, 274, 274 ] ]

$ node test.js
{ length: { y: 2, x: 3 }, matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] }
{ length: { y: 3, x: 2 },
  matrix: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] }
[ [ 22, 28 ], [ 49, 64 ] ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment