Skip to content

Commit

Permalink
Merge pull request #99 from Xuefeng-Zhu/patch-16
Browse files Browse the repository at this point in the history
optimize for loop by pre-calculating size
  • Loading branch information
mateogianolio authored Jan 15, 2017
2 parents 76482c9 + 54c299d commit 6defa6b
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,15 @@
Matrix.prototype.binOp = function(matrix, op) {
var r = this.shape[0], // rows in this matrix
c = this.shape[1], // columns in this matrix
size = r * c,
d1 = this.data,
d2 = matrix.data;

if (r !== matrix.shape[0] || c !== matrix.shape[1])
throw new Error('sizes do not match!');

var i;
for (i = 0; i < r * c; i++)
for (i = 0; i < size; i++)
d1[i] = op(d1[i], d2[i], i);

return this;
Expand Down Expand Up @@ -162,10 +163,11 @@
Matrix.prototype.scale = function (scalar) {
var r = this.shape[0], // rows in this matrix
c = this.shape[1], // columns in this matrix
size = r * c,
d1 = this.data,
i;

for (i = 0; i < r * c; i++)
for (i = 0; i < size; i++)
d1[i] *= scalar;

return this;
Expand Down Expand Up @@ -712,14 +714,15 @@
Matrix.prototype.equals = function (matrix) {
var r = this.shape[0],
c = this.shape[1],
size = r * c,
d1 = this.data,
d2 = matrix.data;

if (r !== matrix.shape[0] || c !== matrix.shape[1] || this.type !== matrix.type)
return false;

var i;
for (i = 0; i < r * c; i++)
for (i = 0; i < size; i++)
if (d1[i] !== d2[i])
return false;

Expand Down Expand Up @@ -784,11 +787,12 @@
Matrix.prototype.map = function (callback) {
var r = this.shape[0],
c = this.shape[1],
size = r * c,
mapped = new Matrix(this),
data = mapped.data,
i;

for (i = 0; i < r * c; i++)
for (i = 0; i < size; i++)
data[i] = callback.call(mapped, data[i], i / c | 0, i % c, data);

return mapped;
Expand All @@ -803,9 +807,10 @@
Matrix.prototype.each = function (callback) {
var r = this.shape[0],
c = this.shape[1],
size = r * c,
i;

for (i = 0; i < r * c; i++)
for (i = 0; i < size; i++)
callback.call(this, this.data[i], i / c | 0, i % c);

return this;
Expand All @@ -819,15 +824,16 @@
**/
Matrix.prototype.reduce = function (callback, initialValue) {
var r = this.shape[0],
c = this.shape[1];
c = this.shape[1],
size = r * c;

if (r * c === 0 && !initialValue)
if (size === 0 && !initialValue)
throw new Error('Reduce of empty matrix with no initial value.');

var i = 0,
value = initialValue || this.data[i++];

for (; i < r * c; i++)
for (; i < size; i++)
value = callback.call(this, value, this.data[i], i / c | 0, i % c);
return value;
};
Expand Down

0 comments on commit 6defa6b

Please sign in to comment.