deepbox/ndarray
Sparse Matrices
Compressed Sparse Row (CSR) format for memory-efficient representation of matrices with many zero entries. Useful for large, sparse datasets and graph-based computations.
CSRMatrix.fromCOO
CSRMatrix.fromCOO(init: CSRMatrixInit): CSRMatrix
Create a CSR matrix from COO (Coordinate) format. Specify non-zero entries as row indices, column indices, and values arrays.
Parameters:
init.rows: number - Number of rowsinit.cols: number - Number of columnsinit.rowIndices: Int32Array - Row indices of non-zero entriesinit.colIndices: Int32Array - Column indices of non-zero entriesinit.values: Float64Array - Values of non-zero entriesCSRMatrix Methods
- .add(other) — Sparse matrix addition
- .sub(other) — Sparse matrix subtraction
- .scale(scalar) — Multiply all values by a scalar
- .multiply(other) — Element-wise multiplication (Hadamard)
- .matvec(vector) — Matrix-vector multiplication
- .matmul(other) — Sparse matrix multiplication
- .transpose() — Transpose the sparse matrix
- .toDense() — Convert to a dense Tensor
- .nnz — Number of non-zero entries
- .shape — [rows, cols] dimensions
sparse.ts
import { CSRMatrix } from "deepbox/ndarray";// Create sparse matrix from coordinate formatconst sparse = CSRMatrix.fromCOO({ rows: 3, cols: 3, rowIndices: new Int32Array([0, 1, 2]), colIndices: new Int32Array([0, 2, 1]), values: new Float64Array([1, 2, 3]),});// Represents: [[1, 0, 0], [0, 0, 2], [0, 3, 0]]console.log(sparse.nnz); // 3 (non-zero entries)const dense = sparse.toDense(); // Full 3×3 tensor// Arithmeticconst scaled = sparse.scale(2); // All values × 2const transposed = sparse.transpose();When to Use
- Matrices where >90% of entries are zero (e.g., adjacency matrices, document-term matrices)
- Graph algorithms with sparse connectivity
- Feature matrices with many zero-valued features
- Memory-constrained environments where dense matrices would be too large