@@ -288,6 +288,17 @@ export class SparseMatrix {
288
288
return this ;
289
289
}
290
290
291
+ /**
292
+ * Returns the non-zero elements of the matrix in coordinate (COO), CSR, or CSC format.
293
+ *
294
+ * @param {Object } [options={}] - Options for output format and sorting.
295
+ * @param {'csr'|'csc' } [options.format] - If specified, returns the result in CSR or CSC format. Otherwise, returns COO format.
296
+ * @param {boolean } [options.sort] - If true, sorts the non-zero elements by their indices.
297
+ * @returns {Object } If no format is specified, returns an object with Float64Array `rows`, `columns`, and `values` (COO format).
298
+ * If format is 'csr', returns { rows, columns, values } in CSR format.
299
+ * If format is 'csc', returns { rows, columns, values } in CSC format.
300
+ * @throws {Error } If an unsupported format is specified.
301
+ */
291
302
getNonZeros ( options = { } ) {
292
303
const cardinality = this . cardinality ;
293
304
/** @type {Float64Array } */
@@ -297,19 +308,19 @@ export class SparseMatrix {
297
308
/** @type {Float64Array } */
298
309
const values = new Float64Array ( cardinality ) ;
299
310
300
- const { format, sort = false } = options ;
311
+ const { format, sort = format !== undefined } = options ;
301
312
302
313
let idx = 0 ;
303
314
this . withEachNonZero ( ( i , j , value ) => {
304
315
rows [ idx ] = i ;
305
316
columns [ idx ] = j ;
306
317
values [ idx ] = value ;
307
318
idx ++ ;
308
- } , sort || format ) ;
319
+ } , sort ) ;
309
320
310
321
if ( ! format ) return { rows, columns, values } ;
311
322
312
- if ( ! [ 'csr' , 'csc' ] . includes ( format . toLowerCase ( ) ) ) {
323
+ if ( ! [ 'csr' , 'csc' ] . includes ( format ) ) {
313
324
throw new Error ( `format ${ format } is not supported` ) ;
314
325
}
315
326
@@ -1501,10 +1512,10 @@ function csrToCsc(csrMatrix, numCols) {
1501
1512
/**
1502
1513
* Converts a matrix from Coordinate (COO) format to Compressed Sparse Row (CSR) format.
1503
1514
* @param {Object } cooMatrix - The matrix in COO format with properties: values, columns, rows.
1504
- * @param {number } [ nbRows=9] - The number of rows in the matrix.
1515
+ * @param {number } nbRows - The number of rows in the matrix.
1505
1516
* @returns {{rows: Float64Array, columns: Float64Array, values: Float64Array} } The matrix in CSR format.
1506
1517
*/
1507
- function cooToCsr ( cooMatrix , nbRows = 9 ) {
1518
+ function cooToCsr ( cooMatrix , nbRows ) {
1508
1519
const { values, columns, rows } = cooMatrix ;
1509
1520
const csrRowPtr = new Float64Array ( nbRows + 1 ) ;
1510
1521
const length = values . length ;
0 commit comments