Using a sparse matrix to reduce memory usage