Allocate space for sparse matrix
S = spalloc(m,n,nz)
S = spalloc(m,n,nz)
creates an all zero
sparse matrix S
of size m
-by-n
with room to hold nz
nonzeros, where nz >= 1
.
The matrix can then be generated column by column without requiring repeated storage
allocation as the number of nonzeros grows.
spalloc(m,n,nz)
is shorthand for
sparse([],[],[],m,n,nz)
If you specify a value of 0
for nz
, then
spalloc
instead sets the value of nz
to
1
.
Use spalloc
to initialize an
n
-by-n
empty sparse matrix with space for
3*n
nonzeros. Then use a for
-loop to fill in
the columns of S
one at a time. The result is a tridiagonal matrix
with about 50% band density.
S = spalloc(n,n,3*n); for j = 1:n ind = [max(j-1,1) j min(j+1,n)]; S(:,j) = sparse(ind,1,round(rand(3,1)),n,1,3); end