矩阵加法、矩阵乘法
* matrix.js
function Matrix(/* Array */a) {
if (typeof a == "undefined") {
a = [];
}
this._a = a;
this.row = this._a.length;
this.col = (typeof this._a[0] == "undefined") ? 0 : this._a[0].length;
}
Matrix.prototype.init = function(/* int */row, /* int */col, val) {
var i,j;
for (i = 0; i < row; i++) {
var t = [];
for (j = 0; j < col; j++) {
t[j] = val;
}
this._a[i] = t;
}
this.row = this._a.length;
this.col = this._a[0].length;
return this;
};
Matrix.prototype.get = function(/* int */x, /* int */y) {
return this._a[x][y];
};
Matrix.prototype.set = function(/* int */x, /* int */y, v) {
this._a[x][y] = v;
return this;
};
Matrix.prototype.toString = function() {
var i, j;
var s = "[";
s += this.get(0, 0);
for (j = 1; j < this.col; j++) {
s += ", " + this.get(0, j);
}
for (i = 1; i < this.row; i++) {
s += "\n " + this.get(i, 0);
for (j = 1; j < this.col; j++) {
s += ", " + this.get(i, j);
}
}
s += "]";
return s;
};
Matrix.add = function(/* Matrix */mat1, /* Matrix */mat2) {
var i, j;
var mat3 = new Matrix();
mat3.init(mat1.row, mat2.col, 0);
for (i = 0; i < mat1.row; i++) {
for (j = 0; j < mat1.col; j++) {
mat3.set(i, j, mat1.get(i, j) + mat2.get(i, j));
}
}
return mat3;
};
Matrix.mul = function(/* Matrix */mat1, /* Matrix */mat2) {
var i, j, k;
var mat3 = new Matrix();
var sum;
mat3.init(mat1.row, mat2.col, 0);
for (i = 0; i < mat3.row; i++) {
for (j = 0; j < mat3.col; j++) {
sum = 0;
for (k = 0; k < mat1.col; k++) {
sum += mat1.get(i, k) * mat2.get(k, j);
}
mat3.set(i, j, sum);
}
}
return mat3;
}
module.exports = Matrix;
* index.js
var Matrix = require("./matrix");
var mat1 = new Matrix([[1,-4],[3,2]]),
mat2 = new Matrix([[2,2],[2,2]]);
mat3 = Matrix.add(mat1, mat2);
console.log(mat3.toString());
var mat4 = new Matrix([[0,1],[2,3],[4,5]]),
mat5 = new Matrix([[6,7,8,9],[0,1,2,3]]),
mat6;
mat6 = Matrix.mul(mat4, mat5);
console.log(mat6.toString());
[mzh@vultr matrix]$ node index.js?
[3, -2
?5, 4]
[0, 1, 2, 3
?12, 17, 22, 27
?24, 33, 42, 51]