Using the C++ Math Library    

Sparse Matrices

The MATLAB C++ Math Library includes routines to create and manipulate sparse matrices. Sparse matrices provides a more efficient storage format for two-dimensional numeric arrays with few non-zero elements. Only two-dimensional numeric arrays can be converted to sparse storage format.

The following table lists the MATLAB C++ Math Library routines to create sparse matrices and perform some basic tasks with them. The sections that follow provide more detail about using these routines. For more detailed information about using sparse arrays, see Using MATLAB. For more detailed information about any of the library routines, see the MATLAB C++ Math Library Reference.

Table 3-2: Sparse Matrix Routines 
To ...
Use ...
Create a sparse matrix
sparse()
Convert a sparse matrix into a full matrix
full()
Replace nonzero sparse matrix elements with ones
spones()

Replace nonzero sparse matrix elements with random numbers.
sprand()
sprandn()
sprandnsym()
Convert a text file into a sparse matrix
spconvert()
Create a sparse identity matrix
speye()
Extract a band or diagonal group of elements from a matrix and create a sparse matrix.
spdiags()
Determine the number of nonzero elements in a numeric matrix.
nnz()
Determine if a matrix has any nonzero elements or if all elements are nonzero.
any() or
all()
Determine the amount of storage allocated for the nonzero elements of a sparse matrix.
nzmax()
Obtain a vector containing all the nonzero elements of a sparse matrix.
nonzeros()
Apply a function to all the nonzero elements of a sparse matrix
spfun()


 Example Program: Creating Arrays and Array I/O (ex1.cpp) Creating a Sparse Matrix