replaced 'apply' for sparse matrices