improved sparse matrix handling