Skip to content

Commit

Permalink
Merge pull request #148 from SaintDako/master
Browse files Browse the repository at this point in the history
add matrix.mapMulti
  • Loading branch information
Dakkers committed Jun 13, 2015
2 parents 72b913a + fab14f2 commit 9a4226f
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 7 deletions.
43 changes: 38 additions & 5 deletions lib/numbers/matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -1301,15 +1301,48 @@ matrix.isStrictlyColumnDD = function (M) {
matrix.map = function (M, f) {
// M is n-by-m (n rows, m columns)
var n = M.length,
m = M[0].length,
i, j;
m = M[0].length,
i, j;

var res = matrix.deepCopy(M);

for (i=0; i<n; i++) {
for (j=0; j<m; j++) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
res[i][j] = f(M[i][j]);
}
}
return res;
}
};

/**
* Applies a function to every element of a vector or matrix (i.e. map).
* Identical to matrix.map, except that the function passed can take an
* arbitrary number of parameters (minimum of 1). Any extra arguments
* passed will be * passed to the apply-er function.
*
* @param {Array} matrix
* @param {Function} function to apply to each element
* @return {Array} matrix operated on
*/
matrix.mapMulti = function (M, f) {
// convert arguments object to an array, ignoring M and f
// extraArgs is of the form [x, arg0, arg1, ...]
var extraArgs = new Array(Object.keys(arguments).length - 1);
for (var k = 1; k < extraArgs.length; k++) {
extraArgs[k] = arguments[k + 1];
}

var n = M.length,
m = M[0].length,
i, j;

var res = matrix.deepCopy(M);

for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
extraArgs[0] = M[i][j];
res[i][j] = f.apply(null, extraArgs);
}
}
return res;
};
37 changes: 35 additions & 2 deletions test/matrix.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -926,9 +926,9 @@ suite('numbers', function () {
[2, 3],
[11, -1]
];
var addOne = function(x) {
var addOne = function (x) {
return x + 1;
}
};

var expected1 = [
[0, 1, 6],
Expand All @@ -949,4 +949,37 @@ suite('numbers', function () {
done();
});

test('should test for applying a function to each element of a matrix with addition parameters', function (done) {
var m1 = [
[1, 3, 5],
[-1, -7, 2],
[5, 5, 4]
];
var m2 = [
[-10, 3],
[4, 9],
[100, 0]
];
var scaleAndAddOne = function (x, alpha) {
return alpha * x + 1;
};

var expected1 = [
[3, 7, 11],
[-1, -13, 5],
[11, 11, 9]
];
var expected2 = [
[-29, 10],
[13, 28],
[301, 1]
];

var res1 = matrix.mapMulti(m1, scaleAndAddOne, 2);
var res2 = matrix.mapMulti(m2, scaleAndAddOne, 3);

assert.deepEqual(res1, expected1);
assert.deepEqual(res2, expected2);
done();
});
});

0 comments on commit 9a4226f

Please sign in to comment.