Search code examples
matlabsparse-matrix

Matlab uint8 sparse


When creating a sparse matrix in Matlab it seems that you can create a sparse matrix either filled with logicals or double valued numbers.

While reading around I understood that Matlab does not have support for other type of sparse matrices, i.e. uint8 or other integers. In my application I know that max(values)==16, and the memory is a crucial thing, therefore I would like to have uint8 sparse matrices.

  • Is there a way of creating a unit8 sparse matrix?

  • If not (most likely), is there any apparent reason of why Matlab has not implemented uint8 sparse matrices?


Solution

  • I can see how using uint8 instead of a double would be no or little improvement.

    A dense matrix is a continuous array so no extra indexing or structuring is required, the position of each element is given by its physical location in the memory.

    But a sparse matrix should additionally require to store each element index, which in case of a 2D matrix would be two integers 32 or 64 bits in size to remember each element row and column number. On top of that there might be some implementation related overhead, such as a tree structure, or something else, used to make sparse matrix operations efficient.

    So it is not 8 uint8 vs 64 double, eight times more less memory usage, but rather (8+32+32+log(n)+..) vs (64+32+32+log(n)+..), which i guess might end up being 10-20% savings at the best?

    Furthermore each memory address now stores 64 bits if I remember correctly, which is one double or 8 uint8 packed together. This means a few extra bits needs to be used per entry just to remember which uint8 packed at that memory address we need, and adds some extra bit masking operations to perform.

    So the guys at Mathworks probably did similar estimate, and decided to just do double sparse matrices.