Using the C++ Math Library    

Creating a Sparse Matrix

To create a sparse matrix in a C++ program, use the MATLAB C++ Math Library sparse() routine. Using this routine, you can create sparse arrays in two ways:

Converting an Existing Matrix into Sparse Format

To create a sparse matrix from a standard numeric array, use the sparse() routine. sparse() converts the numeric array into sparse storage format. The following code fragment creates a sparse matrix from an identity matrix and then converts it to sparse format.

This code displays the identity matrix in full and sparse formats.

Creating a Sparse Matrix from Data

You can also create a sparse matrix by specifying the value and location of all the nonzero elements when you create it. Using sparse(), you specify as arguments:

The following code example illustrates how to create a 8-by-7 sparse matrix from data. This call specifies a single value, 9, for all the nonzero elements of the sparse matrix which is replicated in all nonzero elements by scalar expansion. To see the pattern formed by this sparse matrix, see the output of this code which follows.

This code produces the following output:


 Sparse Matrices Converting a Sparse Matrix to Full Matrix Format