Skip to content

Commit 8516f83

Browse files
committed
feat: add methods scaleRows and scaleColumns
1 parent 41be6e4 commit 8516f83

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,8 @@
5555
"pretty-hrtime": "^1.0.0",
5656
"should": "^9.0.2",
5757
"should-approximately-deep": "^1.1.0"
58+
},
59+
"dependencies": {
60+
"ml-array-utils": "^0.2.4"
5861
}
5962
}

src/matrix.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
'use strict';
22

3+
const arrayUtils = require('ml-array-utils');
4+
35
/**
46
* Real matrix
57
* @class Matrix
@@ -1026,6 +1028,43 @@ class Matrix extends Array {
10261028
return result;
10271029
}
10281030

1031+
/**
1032+
* Returns a row-by-row scaled matrix
1033+
* @param [min=0] - Minimum scaled value
1034+
* @param [max=1] - Maximum scaled value
1035+
*/
1036+
scaleRows(min, max) {
1037+
min = min === undefined ? 0 : min;
1038+
max = max === undefined ? 1 : max;
1039+
var newMatrix = Matrix.empty(this.rows, this.columns);
1040+
for(var i=0; i<this.rows; i++) {
1041+
var scaled = arrayUtils.scale(this.getRow(i), {min, max});
1042+
newMatrix.setRow(i, scaled);
1043+
}
1044+
return newMatrix;
1045+
}
1046+
1047+
/**
1048+
* Returns a column-by-column scaled matrix
1049+
* @param [min=0] - Minimum scaled value
1050+
* @param [max=1] - Maximum scaled value
1051+
*/
1052+
scaleColumns(min, max) {
1053+
min = min === undefined ? 0 : min;
1054+
max = max === undefined ? 1 : max;
1055+
var newMatrix = Matrix.empty(this.rows, this.columns);
1056+
for(var i=0; i<this.columns; i++) {
1057+
var scaled = arrayUtils.scale(this.getColumn(i), {
1058+
min: min,
1059+
max: max
1060+
});
1061+
newMatrix.setColumn(i, scaled);
1062+
}
1063+
return newMatrix;
1064+
}
1065+
1066+
1067+
10291068
/**
10301069
* Returns the Kronecker product (also known as tensor product) between this and other
10311070
* See https://en.wikipedia.org/wiki/Kronecker_product

test/matrix/utility.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,14 @@ describe('utility methods', function () {
9191
transpose.rows.should.equal(3);
9292
transpose.columns.should.equal(2);
9393
});
94+
95+
it('scale rows', function () {
96+
var matrix = new Matrix([[-1,0,1],[6, 9, 7]]);
97+
matrix.scaleRows().to2DArray().should.eql([[0, 1/2, 1],[0, 1, 1/3]]);
98+
});
99+
100+
it('scale columns', function () {
101+
var matrix = new Matrix([[1,2],[-5,3],[2,4]]);
102+
matrix.scaleColumns().to2DArray().should.eql([[6/7, 0],[0, 1/2],[1, 1]]);
103+
});
94104
});

0 commit comments

Comments
 (0)