CSRMatrix Class
Compressed Sparse Row (CSR) matrix representation.CSR format stores a sparse matrix using three arrays:
data: Non-zero values in row-major orderindices: Column indices of non-zero valuesindptr: Row pointers (indptr[i] to indptr[i+1] gives the range for row i)
Properties
Non-zero values stored in row-major order.
Column indices corresponding to each value in
data.Row pointers. Length is
rows + 1. Range [indptr[i], indptr[i+1]) contains the indices for row i.Matrix dimensions
[rows, cols].Number of non-zero elements in the matrix.
Number of rows in the matrix.
Number of columns in the matrix.
Creation
Create a sparse matrix from COO (Coordinate List) format.Parameters:
args.rows(number) - Number of rowsargs.cols(number) - Number of columnsargs.rowIndices(Int32Array) - Row indices of non-zero valuesargs.colIndices(Int32Array) - Column indices of non-zero valuesargs.values(Float64Array) - Non-zero valuesargs.sort(boolean) - Whether to sort entries (default: true)
Create a CSRMatrix directly from CSR format arrays.Parameters:
init.data(Float64Array) - Non-zero valuesinit.indices(Int32Array) - Column indicesinit.indptr(Int32Array) - Row pointersinit.shape(Shape) - Matrix dimensions
Conversion
Convert the sparse matrix to a dense Tensor.Returns: Dense 2D Tensor representation
Arithmetic Operations
Add two sparse matrices element-wise.Both matrices must have the same shape.Parameters:
other(CSRMatrix) - Matrix to add
Subtract another sparse matrix element-wise.Both matrices must have the same shape.Parameters:
other(CSRMatrix) - Matrix to subtract
Multiply all elements by a scalar value.Parameters:
scalar(number) - Value to multiply by
Element-wise multiplication (Hadamard product) with another sparse matrix.Both matrices must have the same shape.Parameters:
other(CSRMatrix) - Matrix to multiply with
Matrix Operations
Matrix-vector multiplication.Computes y = A × x where A is this sparse matrix and x is a dense vector.Parameters:
vector(Tensor | Float64Array) - Dense vector (1D Tensor or Float64Array)
Matrix multiplication with a dense matrix.Computes C = A × B where A is this sparse matrix and B is a dense matrix.Parameters:
dense(Tensor) - Dense matrix (2D Tensor)
Transpose the sparse matrix.Returns: New CSRMatrix representing the transpose
Access Operations
Get a specific element from the matrix.Parameters:
row(number) - Row indexcol(number) - Column index
Create a copy of this matrix.Returns: New CSRMatrix with copied data
Types
Initialization parameters for CSRMatrix constructor.
Example: Sparse Linear System
Example: Sparse Matrix Arithmetic
Performance Notes
-
CSR format is optimized for:
- Row slicing operations
- Matrix-vector multiplication
- Matrix-matrix multiplication where the left operand is sparse
- Memory usage: O(nnz + rows) vs O(rows × cols) for dense matrices
- Best for matrices where nnz is much less than rows × cols (high sparsity)
- Operations like column access are less efficient than row access