Why doesn't SparseArray
automatically remove zero entries? The code
a = SparseArray[{2->22,3->33,5->55,7->77,11->1111,13->1313},13];
b = SparseArray[{1->11,3->33,5->55,7->77,9->99,11->1111},13];
r = DeleteCases[a-b,0]
r //ArrayRules
returns
{{1}->-11,{3}->0,{5}->0,{7}->0,{9}->-99,{11}->0,{2}->22,{13}->1313,{_}->0}
instead of
{{1}->-11,{9}->-99,{2}->22,{13}->1313,{_}->0}
.
Is there a nice way to get rid of zero entries? For instance, when I perform Gaussian elimination on $A\!\in\!\mathbb{Z}^{m\times n}_2$, I use A = Mod[A, 2];
, and suddenly many entries are zero. I don't want to waste memory on them.
Of course I could use
A = SparseArray[DeleteCases[ArrayRules[A], #[[2]] == 0&], {m,n}]
but it seems clumsy to use this often.
Also, when I have a very long sparse row that gets updated frequently and fills up somewhat (Gaussian elimination), is it better to use SparseArray
with +
or Association
with Merge
?
SparseArray
again. $\endgroup$