| MATLAB® | ![]() |
| On this page… |
|---|
There are several commands that provide high-level information about the nonzero elements of a sparse matrix:
nnz returns the number of nonzero elements in a sparse matrix.
nonzeros returns a column vector containing all the nonzero elements of a sparse matrix.
nzmax returns the amount of storage space allocated for the nonzero entries of a sparse matrix.
To try some of these, load the supplied sparse matrix west0479, one of the Harwell-Boeing collection.
load west0479 whos Name Size Bytes Class Attributes M_full 1100x1100 9680000 double M_sparse 1100x1100 5004 double sparse west0479 479x479 24564 double sparse
This matrix models an eight-stage chemical distillation column.
Try these commands.
nnz(west0479)
ans =
1887
format short e
west0479
west0479 =
(25,1) 1.0000e+00
(31,1) -3.7648e-02
(87,1) -3.4424e-01
(26,2) 1.0000e+00
(31,2) -2.4523e-02
(88,2) -3.7371e-01
(27,3) 1.0000e+00
(31,3) -3.6613e-02
(89,3) -8.3694e-01
(28,4) 1.3000e+02
.
.
.
nonzeros(west0479);
ans =
1.0000e+00
-3.7648e-02
-3.4424e-01
1.0000e+00
-2.4523e-02
-3.7371e-01
1.0000e+00
-3.6613e-02
-8.3694e-01
1.3000e+02
.
.
.
Note Use Ctrl+C to stop the nonzeros listing at any time. |
Note that initially nnz has the same value as nzmax by default. That is, the number of nonzero elements is equivalent to the number of storage locations allocated for nonzeros. However, MATLAB® software does not dynamically release memory if you zero out additional array elements. Changing the value of some matrix elements to zero changes the value of nnz, but not that of nzmax.
However, you can add as many nonzero elements to the matrix as desired. You are not constrained by the original value of nzmax.
For any matrix, full or sparse, the find function returns the indices and values of nonzero elements. Its syntax is
[i,j,s] = find(S)
find returns the row indices of nonzero values in vector i, the column indices in vector j, and the nonzero values themselves in the vector s. The example below uses find to locate the indices and values of the nonzeros in a sparse matrix. The sparse function uses the find output, together with the size of the matrix, to recreate the matrix.
[i,j,s] = find(S) [m,n] = size(S) S = sparse(i,j,s,m,n)
It is often useful to use a graphical format to view the distribution of the nonzero elements within a sparse matrix. The MATLAB spy function produces a template view of the sparsity structure, where each point on the graph represents the location of a nonzero array element.
For example:
spy(west0479)

![]() | Constructing Sparse Matrices | Sparse Matrix Operations | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |