sparse
Creates a sparse matrix, or converts a full matrix to sparse form.
Category: Mathematics > Sparse Matrices
Syntax
S = sparse(A)
Converts the full matrix A to sparse storage.
S = sparse(m, n)
Creates an m-by-n sparse matrix of zeros.
S = sparse(i, j, v)
Creates a matrix with S(i(k), j(k)) = v(k); repeated positions are added together.
S = sparse(i, j, v, m, n)
Same, with an explicit size m-by-n.
S = sparse(i, j, v, m, n, nzmax)
Also reserves space for nzmax nonzeros.
Description
A sparse matrix keeps only its nonzero entries, which lets large matrices that are mostly zeros, such as finite-difference grids or graphs, be handled efficiently. Display lists each stored entry as (row,column) value.
Arithmetic follows simple rules: sparse times sparse is sparse, sparse plus a nonzero scalar becomes full, and most elementwise functions keep sparsity if f(0) = 0. Use full to convert back, issparse to test, and find to list the entries.
Building from triplets (i, j, v) is the fast way to assemble a matrix. Duplicate positions are summed, which is convenient for assembling finite-element matrices.
Input arguments
A- Numeric or logical matrix.
i, j- Row and column indices of the entries, as vectors of positive integers.
v- Values for the entries; a scalar is expanded to all positions.
m, n- Number of rows and columns.
Output arguments
S- Sparse matrix. Zero entries are not shown when it is displayed.
Example
Triplets, a sum and a conversion
S = sparse([1 2 3 3], [1 2 3 3], [4 5 6 1])
full(S)
T = sparse([1 0 2; 0 0 3])
size(sparse(2, 3))
S =
(1,1) 4
(2,2) 5
(3,3) 7
ans = 3×3
4 0 0
0 5 0
0 0 7
T =
(1,1) 1
(1,3) 2
(2,3) 3
ans = 1×2
2 3
Notes
Complex values are not kept: the imaginary part is dropped when building a sparse matrix. MatLivre stores sparse matrices densely, so they save no memory, and sizes above 200 million elements are rejected. Results and display match MATLAB for ordinary sizes.