Skip to content

Commit 338dfe9

Browse files
authored
fix: #3530 throw an error when trying to flatten a SparseMatrix (#3536)
1 parent f74d636 commit 338dfe9

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/function/matrix/flatten.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,24 @@ export const createFlatten = /* #__PURE__ */ factory(name, dependencies, ({ type
2121
*
2222
* concat, resize, size, squeeze
2323
*
24-
* @param {Matrix | Array} x Matrix to be flattened
25-
* @return {Matrix | Array} Returns the flattened matrix
24+
* @param {DenseMatrix | Array} x Matrix to be flattened
25+
* @return {DenseMatrix | Array} Returns the flattened matrix
2626
*/
2727
return typed(name, {
2828
Array: function (x) {
2929
return flattenArray(x)
3030
},
3131

32-
Matrix: function (x) {
32+
DenseMatrix: function (x) {
3333
// Return the same matrix type as x (Dense or Sparse Matrix)
3434
// Return the same data type as x
3535
return x.create(flattenArray(x.valueOf(), true), x.datatype())
36+
},
37+
38+
SparseMatrix: function (_x) {
39+
throw new TypeError('SparseMatrix is not supported by function flatten ' +
40+
'because it does not support 1D vectors. ' +
41+
'Convert to a DenseMatrix or Array first. Example: flatten(x.toArray())')
3642
}
3743
})
3844
})

test/unit-tests/function/matrix/flatten.test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import assert from 'assert'
22
import math from '../../../../src/defaultInstance.js'
33
const matrix = math.matrix
44
const flatten = math.flatten
5+
const sparse = math.sparse
56

67
describe('flatten', function () {
78
it('should flatten an empty array', function () {
@@ -39,6 +40,10 @@ describe('flatten', function () {
3940
assert.deepStrictEqual(flatten(matrix([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])), matrix([1, 2, 3, 4, 5, 6, 7, 8]))
4041
})
4142

43+
it('should throw an error in case of SparseMatrix input', function () {
44+
assert.throws(function () { flatten(sparse([1, 2])) }, /TypeError: SparseMatrix is not supported/)
45+
})
46+
4247
it('should throw an error on invalid arguments', function () {
4348
assert.throws(function () { flatten() }, /TypeError: Too few arguments/)
4449
assert.throws(function () { flatten([], 2) }, /TypeError: Too many arguments/)

0 commit comments

Comments
 (0)