Skip to content

Commit

Permalink
feat: add methods scaleRows and scaleColumns
Browse files Browse the repository at this point in the history
  • Loading branch information
stropitek committed Jul 25, 2016
1 parent 41be6e4 commit 8516f83
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,8 @@
"pretty-hrtime": "^1.0.0",
"should": "^9.0.2",
"should-approximately-deep": "^1.1.0"
},
"dependencies": {
"ml-array-utils": "^0.2.4"
}
}
39 changes: 39 additions & 0 deletions src/matrix.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const arrayUtils = require('ml-array-utils');

/**
* Real matrix
* @class Matrix
Expand Down Expand Up @@ -1026,6 +1028,43 @@ class Matrix extends Array {
return result;
}

/**
* Returns a row-by-row scaled matrix
* @param [min=0] - Minimum scaled value
* @param [max=1] - Maximum scaled value
*/
scaleRows(min, max) {
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
var newMatrix = Matrix.empty(this.rows, this.columns);
for(var i=0; i<this.rows; i++) {
var scaled = arrayUtils.scale(this.getRow(i), {min, max});
newMatrix.setRow(i, scaled);
}
return newMatrix;
}

/**
* Returns a column-by-column scaled matrix
* @param [min=0] - Minimum scaled value
* @param [max=1] - Maximum scaled value
*/
scaleColumns(min, max) {
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
var newMatrix = Matrix.empty(this.rows, this.columns);
for(var i=0; i<this.columns; i++) {
var scaled = arrayUtils.scale(this.getColumn(i), {
min: min,
max: max
});
newMatrix.setColumn(i, scaled);
}
return newMatrix;
}



/**
* Returns the Kronecker product (also known as tensor product) between this and other
* See https://en.wikipedia.org/wiki/Kronecker_product
Expand Down
10 changes: 10 additions & 0 deletions test/matrix/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,14 @@ describe('utility methods', function () {
transpose.rows.should.equal(3);
transpose.columns.should.equal(2);
});

it('scale rows', function () {
var matrix = new Matrix([[-1,0,1],[6, 9, 7]]);
matrix.scaleRows().to2DArray().should.eql([[0, 1/2, 1],[0, 1, 1/3]]);
});

it('scale columns', function () {
var matrix = new Matrix([[1,2],[-5,3],[2,4]]);
matrix.scaleColumns().to2DArray().should.eql([[6/7, 0],[0, 1/2],[1, 1]]);
});
});

0 comments on commit 8516f83

Please sign in to comment.