Main Content

sparse

Create sparse matrix

Description

example

S = sparse(A) 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.

example

S = sparse(m,n) generates an m-by-n all zero sparse matrix.

example

S = sparse(i,j,v) generates a sparse matrix 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.

example

S = sparse(i,j,v,m,n) specifies the size of S as m-by-n.

example

S = sparse(i,j,v,m,n,nz) allocates space for nz nonzero elements. Use this syntax to allocate extra space for nonzero values to be filled in after construction.

Examples

collapse all

Create a 10,000-by-10,000 full storage identity matrix.

A = eye(10000);
whos A
  Name          Size                   Bytes  Class     Attributes

  A         10000x10000            800000000  double              

This matrix uses 800-megabytes of memory.

Convert the matrix to sparse storage.

S = sparse(A);
whos S
  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 = sparse(10000,5000)
S = 
   All zero sparse: 10000x5000

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 = 
 (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.

size(S)
ans = 1×2

        1500        1500

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)
N = 10
N_alloc = nzmax(S)
N_alloc = 100

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.

[i,j,v]
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 = sparse(i,j,v)
S = 
   (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: 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, sparse applies the any function.

  • For double values, sparse applies the sum function.

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: 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.

Data Types: double

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]).

Data Types: double

Limitations

  • If any of the inputs i,j or m,n are larger than 2^31-1 for 32-bit platforms, or 2^48-1 on 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 accumarray function has similar accumulation behavior to that of sparse.

    • accumarray groups data into bins using n-dimensional subscripts, but sparse groups data into bins using 2-D subscripts.

    • accumarray adds elements that have identical subscripts into the output by default, but can optionally apply any function to the bins. sparse applies the sum function to elements that have identical subscripts into the output (for double values) or applies the any function (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

Version History

Introduced before R2006a

expand all