MATLAB: Do I receive an “Out of memory” error when comparing if the elements in a sparse matrix are smaller than a certain value

indexindexinglogical?MATLABsparcesparse

Having a very large sparse matrix (> 10000×10000), with most of the elements equal to zero, and then indexing the matrix by using a logical operator such as:
a = largeMatrix(largeMatrix < comparisonDouble);
Where "comparisonDouble" is a positive value, the operation may result in the following error:
??? Error using ==> lt
Out of memory. Type HELP MEMORY for your options.

Best Answer

This error is caused because the condition "< comparisonDouble" also applies to all elements that are equal to zero. The resulting logical sparse matrix thus contains only a few zeros, and most elements are ones, so it's size approaches that of a full sparse matrix.
To work around this issue, first extract all elements that are "> 0", and then apply the condition "< comparisonDouble" to them, like this:
a = largeMatrix(largeMatrix(largeMatrix > 0) < comparisonDouble);