sparse - Create sparse matrix - MATLAB
Syntax
Description
converts a full matrix into sparse form by squeezing out any zero elements. If a
matrix contains many zeros, converting the matrix to sparse storage saves
memory.S = sparse(A)
generates a sparse matrix S = sparse(i,j,v)S from the triplets
i, j, and v such
that S(i(k),j(k)) = v(k). The
max(i)-by-max(j) output matrix has
space allotted for length(v) nonzero elements.
If the inputs i, j, and
v are vectors or matrices, they must have the same number
of elements. Alternatively, the argument v and/or one of the
arguments i or j can be scalars.
Examples
collapse all
Create a 10,000-by-10,000 full storage identity matrix.
Name Size Bytes Class Attributes A 10000x10000 800000000 double
This matrix uses 800-megabytes of memory.
Convert the matrix to sparse storage.
Name Size Bytes Class Attributes S 10000x10000 240008 double sparse
In sparse form, the same matrix uses roughly 0.25-megabytes of memory. In this case, you can avoid full storage completely by using the speye function, which creates sparse identity matrices directly.
S = 10000×5000 sparse double matrix
All zero
Create a 1500-by-1500 sparse matrix from the triplets i, j, and v.
i = [900 1000]; j = [900 1000]; v = [10 100]; S = sparse(i,j,v,1500,1500)
S = 1500×1500 sparse double matrix (2 nonzeros)
(900,900) 10
(1000,1000) 100
When you specify a size larger than max(i) -by- max(j), the sparse function pads the output with extra rows and columns of zeros.
Create a sparse matrix with 10 nonzero values, but which has space allocated for 100 nonzero values.
S = sparse(1:10,1:10,5,20,20,100); N = nnz(S)
The spalloc function is a shorthand way to create a sparse matrix with no nonzero elements but which has space allotted for some number of nonzeros.
Use repeated subscripts to accumulate values into a single sparse matrix that would otherwise require one or more loops.
Create a column vector of data and two column vectors of subscripts.
i = [6 6 6 5 10 10 9 9]'; j = [1 1 1 2 3 3 10 10]'; v = [100 202 173 305 410 550 323 121]';
Visualize the subscripts and values side-by-side.
ans = 8×3
6 1 100
6 1 202
6 1 173
5 2 305
10 3 410
10 3 550
9 10 323
9 10 121
Use the sparse function to accumulate the values that have identical subscripts.
S = 10×10 sparse double matrix (4 nonzeros)
(6,1) 475
(5,2) 305
(10,3) 960
(9,10) 444
Input Arguments
collapse all
Input matrix, specified as a full or sparse matrix. If A is
already sparse, then sparse(A) returns A.
Data Types: single | double | logical
Complex Number Support: Yes
Subscript pairs, specified as separate arguments of scalars, vectors, or matrices.
Corresponding elements in i and j
specify S(i,j) subscript pairs, which determine the
placement of the values in v into the output.
i and j must have the same data
type. If either i or j is a vector or
matrix, then the other input can be a scalar or can be a vector or matrix
with the same number of elements. In that case, sparse
uses i(:) and j(:) as the
subscripts.
If i and j have identical values for
several elements in v, then sparse
aggregates the values in v that have repeated indices.
The aggregation behavior depends on the data type of the values in
v:
For logical values,
sparseapplies theanyfunction.For double values,
sparseapplies thesumfunction.
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical
Values, specified as a scalar, vector, or matrix. If v is
a vector or matrix, then one of the inputs i or j must
also be a vector or matrix with the same number of elements.
Any elements in v that are zero are ignored,
as are the corresponding subscripts in i and j.
However, if you do not specify the dimension sizes of the output, m and n,
then sparse calculates the maxima m =
max(i) and n = max(j) before ignoring
any zero elements in v.
Data Types: single | double | logical
Complex Number Support: Yes
Size of each dimension, specified as separate arguments of integer
values. If you specify m (the row size), you also
must specify n (the column size).
If you do not specify m and n,
then sparse uses the default values m
= max(i) and n = max(j). These maxima
are computed before any zeros in v are removed.
Since R2025a
Output data type, specified as "double",
"single", or "logical".
Storage allocation for nonzero elements, specified as a nonnegative integer.
nz generally must be greater than or equal to
max([numel(i), numel(j), numel(v), 1]). However, if
the sizes of i, j, and
v allow you to specify a value of
0 for nz, then
sparse instead sets the value to
1.
For a sparse matrix, S, the nnz function returns the number of nonzero
elements in the matrix, and the nzmax function
returns the amount of storage allocated for nonzero matrix elements.
If nnz(S) and nzmax(S) return
different results, then more storage might be allocated than is actually
required. For this reason, set nz only in anticipation
of later fill-in.
If you do not specify nz, then sparse uses a default
value of max([numel(i), numel(j), numel(v), 1]).
Output Arguments
collapse all
Output matrix, returned as a sparse matrix.
Limitations
If any of the inputs
i,jorm,nare larger than2^31-1for 32-bit platforms, or2^48-1on 64-bit platforms, then the sparse matrix cannot be constructed.
Tips
MATLAB® stores sparse matrices in compressed sparse column format. For more information, see John R. Gilbert, Cleve Moler, and Robert Schreiber's Sparse Matrices In MATLAB: Design and Implementation.
The
accumarrayfunction has similar accumulation behavior to that ofsparse.accumarraygroups data into bins using n-dimensional subscripts, butsparsegroups data into bins using 2-D subscripts.accumarrayadds elements that have identical subscripts into the output by default, but can optionally apply any function to the bins.sparseapplies thesumfunction to elements that have identical subscripts into the output (for double values) or applies theanyfunction (for logical values).
References
[1] Gilbert, John R., Cleve Moler, and Robert Schreiber. “Sparse Matrices in MATLAB: Design and Implementation.” SIAM Journal on Matrix Analysis and Applications 13, no. 1 (January 1992): 333–356. https://doi.org/10.1137/0613024.
[2] Chen, Yanqing, Timothy A. Davis, William W. Hager, and Sivasankaran Rajamanickam. “Algorithm 887: CHOLMOD, Supernodal Sparse Cholesky Factorization and Update/Downdate.” ACM Transactions on Mathematical Software 35, no. 3 (October 2008): 1–14. https://doi.org/10.1145/1391989.1391995.
Extended Capabilities
expand all
Usage notes and limitations:
The number of rows, columns, and nonzero elements must each have a value less than
intmax.In MATLAB, you can construct a sparse matrix using scalar expansion. For example,
sparse([1 2],[3 4], 2). For code generation, you can only use scalar expansion for compile-time scalar inputs. Variable-size arrays that are scalar at run time are not expanded.
The sparse function
supports GPU array input with these usage notes and limitations:
Allocating storage for nonzero elements using the
nzinput argument is not supported.
For more information about creating and using sparse GPU arrays, see Work with Sparse Arrays on a GPU (Parallel Computing Toolbox).
Version History
Introduced before R2006a
expand all
You can specify the output data type by specifying the
typename argument as "double",
"single", or "logical". You can also
create a single-precision sparse matrix by providing single-precision input data to
the sparse function.
The default display for sparse matrices with double values now
explicitly identifies the matrices as sparse. The display also now includes the
dimensions, class, and number of nonzero entries in the matrix. For example:
A = [0 0 0 5; 0 2 0 0; 1 3 0 0; 0 0 4 0]; sparse(A)
4×4 sparse double matrix (5 nonzeros) (3,1) 1 (2,2) 2 (3,2) 3 (4,3) 4 (1,4) 5
The default display for sparse matrices with logical values already
identified the matrices as sparse and included dimensions and class, but the display
now also includes the number of nonzero entries.
The subscript inputs i and j can now be
integer data types. Also, when the third input of the syntax
sparse(i,j,v) contains logical values and there are repeated
subscripts in i and j, the
sparse function now applies a logical any
operation to the values with repeated subscripts.