Main Content

Code Generation for Sparse Matrices

Sparse matrices provide efficient storage in memory for arrays with many zero elements. Sparse matrices can provide improved performance and reduced memory usage for generated code. Computation time on sparse matrices scales only with the number of operations on nonzero elements.

Functions for creating and manipulating sparse matrices are listed in Sparse Matrices. To check if a function is supported for code generation, see the function reference page. Code generation does not support sparse matrix inputs created by using sparse for all functions.

Code Generation Guidelines

Initialize matrices by using sparse constructors to maximize your code efficiency. For example, to construct a 3-by-3 identity matrix, use speye(3,3) rather than sparse(eye(3,3)).

Indexed assignment into sparse matrices incurs an overhead compared to indexed assignment into full matrices. For example:

S = speye(10);
S(7,7) = 42;

As in MATLAB®, sparse matrices are stored in compressed sparse column format. When you insert a new nonzero element into a sparse matrix, all subsequent nonzero elements must be shifted downward, column by column. These extra manipulations can slow performance. See Accessing Sparse Matrices.

Code Generation Limitations

Code generation does not support sparse matrices for Simulink® signals, parameters, or data store memory. Simulation state save and restore is not supported.

To generate code that uses sparse matrices, dynamic memory allocation must be enabled. To store the changing number of nonzero elements, and their values, sparse matrices use variable-size arrays in the generated code. To change dynamic memory allocation settings, see Control Memory Allocation for Variable-Size Arrays in a MATLAB Function Block. Because sparse matrices use variable-size arrays for dynamic memory allocation, limitations on Variable-Size Data also apply to sparse matrices.

You cannot assign sparse data to data that is not sparse. The generated code uses distinct data type representations for sparse and full matrices. To convert to and from sparse data, use the explicit sparse and full conversion functions.

You cannot define a sparse matrix with competing size specifications. The code generator fixes the size of the sparse matrix when it produces the corresponding data type definition in C/C++. As an example, the function foo causes an error in code generation:

function y = foo(n)
%#codegen
if n > 0
    y = sparse(3,2);
else
    y = sparse(4,3);
end

Logical indexing into sparse matrices is not supported for code generation. For example, this syntax causes an error:

S = magic(3);
S(S > 7) = 42;

For sparse matrices, you cannot delete array elements by assigning empty arrays:

S(:,2) = [];

See Also

| | |

Related Topics