I am interested in filtering a sparse matrix, where the values are between zero and one. I do it in the following manner.
s = SparseArray[RandomInteger[{1, 20}, {5, 2}] -> RandomReal[1, 5]]
fs = Select[s["NonzeroValues"], # > 0.5 &]; // AbsoluteTiming
fs
But I little bit confused by the result, I didn't get a sparse matrix (in the documentation written in an unclear way when Select
return not sparse matrix Select documentation). Also, I am interesting to improve a runtime
Select
nor what your issues with the runtime are. What is the output that you actually want? $\endgroup$SparseArray[Subtract[1, UnitStep[Subtract[0.5, s]]]]
is what you look for... $\endgroup$EvenQ
which embraces the background value (0
) of the spare array. That's why the output is created as sparse vector with the same background value. In the second example, it is clear that the background value is ruled out so that there is some good reason to make the return value a dense, packed vector (a dense vector is the most appropriate data type for such data). But when you applySelect
tos["NonzeroValues"]
, which is a dense array, then you will of course gain a dense array as return value. $\endgroup$