spalloc

Creates an empty sparse matrix with room reserved for nonzeros.

Category: Mathematics > Sparse Matrices

Syntax

S = spalloc(m, n, nzmax)

Returns an m-by-n all-zero sparse matrix with space for nzmax nonzeros.

Description

spalloc(m, n, nzmax) is sparse(m, n) with a hint about how many entries will be filled in later. When a matrix is built by assigning elements one at a time, reserving the space avoids repeated reallocation. The matrix is still all zeros until you assign to it.

Input arguments

m, n
Number of rows and columns.
nzmax
Number of nonzeros to reserve space for.

Output arguments

S
Sparse matrix with nnz(S) = 0.

Example

Reserve, then fill

S = spalloc(3, 3, 4);
nnz(S)
S(1, 1) = 5;
S(3, 2) = 7;
nnz(S)
full(S)
Output
ans = 0
ans = 2
ans = 3×3

     5     0     0
     0     0     0
     0     7     0

See also

sparse nzmax nnz speye