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.
mwArray A,B; A = eye(12); cout << A << endl; B = sparse(A); cout << B << endl;
This code displays the identity matrix in full and sparse formats.
[ 1 0 0 0 0 0 0 0 0 0 0 0; 0 1 0 0 0 0 0 0 0 0 0 0; 0 0 1 0 0 0 0 0 0 0 0 0; 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 1 0 0 0 0 0 0 0; 0 0 0 0 0 1 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 0 0 1 ] ans = (1,1) 1 (2,2) 1 (3,3) 1 (4,4) 1 (5,5) 1 (6,6) 1 (7,7) 1 (8,8) 1 (9,9) 1 (10,10) 1 (11,11) 1 (12,12) 1
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:
i
and j
, that specify the row and column subscriptss
, containing the real or complex data you want to store in the sparse matrix. Vectors i
, j
and s
should all have the same length.m
and n
, that specify the dimensions of the sparse matrix to be createdThe 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.
// declare C++ arrays of index values double inums[] = {3,4,5,4,5,6}; double jnums[] = {4,3,3,5,5,4}; // declare MATLAB arrays mwArray S; mwArray i(1,6,inums,NULL); // Use constructors to create mwArray j(1,6,jnums,NULL); // initialized index vectors // create sparse matrix S = sparse(i, j, 9, 8, 7); cout << S << endl; cout << full(S) << endl;
This code produces the following output:
(4,3) 9 (5,3) 9 (3,4) 9 (6,4) 9 (4,5) 9 (5,5) 9 [ 0 0 0 0 0 0 0; 0 0 0 0 0 0 0; 0 0 0 9 0 0 0; 0 0 9 0 9 0 0; 0 0 9 0 9 0 0; 0 0 0 9 0 0 0; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0; ]
![]() | Sparse Matrices | Converting a Sparse Matrix to Full Matrix Format | ![]() |