sparse - Create sparse matrix - MATLAB (original) (raw)

Syntax

Description

S = sparse([A](#bul5blm-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](#bul5blm-mn)) generates an m-by-n all zero sparse matrix.

example

S = sparse([i,j](#bul5blm-ij),[v](#bul5blm-v)) generates a sparse matrix S from the triplets i,j, and v such thatS(i(k),j(k)) = v(k). Themax(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](#bul5blm-ij),[v](#bul5blm-v),[m,n](#bul5blm-mn)) specifies the size of S as m-by-n.

example

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

example

Examples

collapse all

Save Memory Using Sparse Storage

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.

Sparse Matrix of All Zeros

S = 10000x5000 sparse double matrix All zero

Sparse Matrix of Nonzeros with Specified Size

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 = 1500x1500 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.

Preallocate Storage in Sparse Matrix

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.

Accumulate Values into Sparse Matrix

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 = 10x10 sparse double matrix (4 nonzeros) (6,1) 475 (5,2) 305 (10,3) 960 (9,10) 444

Input Arguments

collapse all

A — Input matrix

full matrix | sparse matrix

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

i,j — Subscript pairs (as separate arguments)

scalars | vectors | matrices

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

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical

v — Values

scalar | vector | matrix

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

m,n — Size of each dimension (as separate arguments)

integer values

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

nz — Storage allocation for nonzero elements

nonnegative integer

Storage allocation for nonzero elements, specified as a nonnegative integer.nz generally must be greater than or equal tomax([numel(i), numel(j), numel(v), 1]). However, if the sizes of i, j, andv allow you to specify a value of0 for nz, thensparse instead sets the value to1.

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

Tips

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

C/C++ Code Generation

Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

Thread-Based Environment

Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

GPU Arrays

Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

The sparse function fully supports GPU arrays. To run the function on a GPU, specify the input data as a gpuArray (Parallel Computing Toolbox). For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Distributed Arrays

Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

Usage notes and limitations:

For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).

Version History

Introduced before R2006a

expand all

R2024b: Default display for sparse matrices includes additional information

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.

R2020a: Support for integer subscripts and logical aggregation

The subscript inputs i and j can now be integer data types. Also, when the third input of the syntaxsparse(i,j,v) contains logical values and there are repeated subscripts in i and j, thesparse function now applies a logical any operation to the values with repeated subscripts.