Storing sparse matrix – list of lists LIL
Usually matrices in C++ programs are represented as two-dimensional arrays. Memory requirement of such array is proportional to m×n
, where m
and n
are the height and width of this array.
Things look differently if the matrix we need to store is a sparse matrix. Sparse matrix is a matrix which most elements have default value (often zero) and only few elements have other value. Storing such matrix in two-dimensional array would be a big waste of memory space, especially when it is large-sized and the sparsity level is high. Such array can be stored in reduced space with no information loss and with only slight deterioration in performance.
List of lists: Efficient representation of sparse array
One of possible approaches to store sparse array is a list of lists (LIL) method. The whole array is represented as list of rows and each row is represented as list of pairs: position (index) in the row and the value. Only elements with value other than default (zero in presented case) are stored. For the best performance the lists should be sorted in order of ascending keys.
Let’s consider one-dimensional array for simplicity. It contains a huge amount of elements, but only the initial ones are presented below. Three elements are of non-zero value.
It can be represented as following list of pairs (index, value):
The representation of 2D sparse matrix is similar; just store rows with its sequential number (index) in the another list. You have list (of rows) of lists (row’s elements).
Example of implementation in C++
CSparse1DArray is example draft C++11 implementation of fixed-size 1D sparse array of integers, based on list approach. The value of skipped fields can be customized, it’s 0 by default.
Ready solutions
It may be clever to use already implemented solutions. For C++ usage, check out the possibilities of boost library for sparse matrices. For Python try sparse matrices in SciPy library.