diff --git a/lib/type/matrix/SparseMatrix.js b/lib/type/matrix/SparseMatrix.js index 93fbbdc87..dbe9c1fbb 100644 --- a/lib/type/matrix/SparseMatrix.js +++ b/lib/type/matrix/SparseMatrix.js @@ -505,22 +505,15 @@ function factory (type, config, load, typed) { var _getValueIndex = function(i, top, bottom, index) { // check row is on the bottom side - if (bottom - top === 0 || i > index[bottom - 1]) + if (bottom - top === 0) return bottom; - // loop until we find row index - while (top < bottom) { - // point in the middle (fast integer division) - var p = ~~((top + bottom) / 2); - // row @ p - var r = index[p]; - // check we have to look on the top side, bottom side or we found the row - if (i < r) - bottom = p; - else if (i > r) - top = p + 1; - else - return p; + // loop rows [top, bottom[ + for (var r = top; r < bottom; r++) { + // check we found value index + if (index[r] === i) + return r; } + // we did not find row return top; }; diff --git a/test/type/matrix/SparseMatrix.test.js b/test/type/matrix/SparseMatrix.test.js index 38f5bf4ad..7915943fc 100644 --- a/test/type/matrix/SparseMatrix.test.js +++ b/test/type/matrix/SparseMatrix.test.js @@ -631,6 +631,24 @@ describe('SparseMatrix', function() { assert.equal(m.get([5, 1]), 4); assert.equal(m.get([5, 5]), -1); }); + + it('should get matrix element - Issue #450', function () { + var m = new SparseMatrix({ + mathjs: 'SparseMatrix', + values: [ 3, 10, 3, 9, 7, 4, 8, 8, 8, 7, 7, 9, -2, 5, 9, 2, 3, -1, 13 ], + index: [ 1, 0, 3, 1, 2, 5, 4, 2, 3, 2, 3, 4, 0, 3, 4, 5, 1, 5, 4 ], + ptr: [ 0, 3, 7, 9, 12, 16, 19 ], + size: [ 6, 6 ], + datatype: undefined + }); + + assert.equal(m.get([0, 0]), 10); + assert.equal(m.get([1, 0]), 3); + assert.equal(m.get([4, 1]), 8); + assert.equal(m.get([5, 1]), 4); + assert.equal(m.get([4, 5]), 13); + assert.equal(m.get([5, 5]), -1); + }); }); describe('set', function () {