diff --git a/lib/function/statistics/mean.js b/lib/function/statistics/mean.js index 288dadbfc..c71272d79 100644 --- a/lib/function/statistics/mean.js +++ b/lib/function/statistics/mean.js @@ -28,7 +28,7 @@ module.exports = function (math) { else if (arguments.length == 2) { // mean([a, b, c, d, ...], dim) // TODO: implement support for calculating the mean over specified dimension - throw new Error('Specifying a dimension is not yet implemented...'); + return _nmean(arguments[0], arguments[1]-1); } else { throw new SyntaxError('Wrong number of parameters'); @@ -40,6 +40,25 @@ module.exports = function (math) { } }; + /** + * Calculate the mean value in an n-dimensional array, returning a + * n-1 dimensional array + * @param {Array} array + * @param {Number} dimension + * @return {Number} mean + * @private + */ + function _nmean(array, dim){ + var sum, len, tmp; + sum = collection.reduce(array, dim, math.add); + tmp = array; + while(--dim){ + tmp = tmp[0]; + } + len = tmp.length; + return math.divide(sum/len); + }; + /** * Recursively calculate the mean value in an n-dimensional array * @param {Array} array diff --git a/test/function/statistics/mean.test.js b/test/function/statistics/mean.test.js index d0acbd739..1d7ee042e 100644 --- a/test/function/statistics/mean.test.js +++ b/test/function/statistics/mean.test.js @@ -36,6 +36,15 @@ describe('mean', function() { ])), 5); }); + it('should return the mean value along a dimension on a matrix', function() { + assert.deepEqual(math.mean([ + [2, 6], + [4, 10]],2), [4, 7]); + assert.deepEqual(math.mean([ + [2, 6], + [4, 10]],1), [3, 8]); + }); + it('should throw an error if called with invalid number of arguments', function() { assert.throws(function() {math.mean()}); });