Mathematica doesn't notice when an entry coincides with the default value:

(IdentityMatrix[2, SparseArray] - IdentityMatrix[2, SparseArray])["NonzeroPositions"]

{{1, 1}, {2, 2}}

How to make it notice this?


1 Answer 1


As corey979 pointed out, wrap it with SparseArray. Moreover, it is also discussed in the section "Possible Issues" in the documentation of SparseArray.

In any cases, automatic "nullifying" of zero entries would harm performance as the internal structure of the sparse array (i.e., A["RowPointers"], A["ColumnIndices"], and A["NonzeroPositions"]) would have to be recomputed. (Note that internally, SparseArrays are stored in the CRS format. See also here for the Mathematica-specfic details.) As few zero-valued nonzero entries usually do not harm, it is a good thing to have it under user control.

There are even use cases in which an automatic "nullifying" of zero-valued nonzero entries would be harmful (although I cannot recall a case where that was an issue when using only in-built functions). For example, I frequently use the MKL Pardiso solver through library link. That enables me to factor a matrix A, then change only the values of A, and recycle most of the data that Pardiso computed internally -- provided that A["NonzeroPositions"] does not change. That's very useful, e.g., for Newton's method. It would be a tedious task if Mathematica would "nullify" entries "at random".


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.