Thanks for the lightning response and the slick one-liner!
Here’s a quick comparison of the hack I have been working with, your two approaches, and one i found here.
using BenchmarkTools, SparseArrays, Unzip
x = rand(1000,1000)
d = 0.01
@btime begin
m = x .< d
i,j, = findnz(m)
xs = sparse(i ,j, view(x, m), size(x)...)
end
# 1.489 ms (38 allocations: 851.00 KiB)
@btime xs = sparse(x .* (x .< d))
# 2.482 ms (12 allocations: 7.79 MiB)
@btime begin
CI = findall(x .< d)
i, j = unzip(Tuple.(CI))
xs = sparse(i, j, view(x, CI), size(x)...)
end
# 1.190 ms (45 allocations: 927.47 KiB)
@btime begin
CI = findall(x .< d)
CI′ = reinterpret(Int, reshape(CI, 1, :))
xs = sparse(view(CI′, 1, :), view(CI′, 2, :), view(x, CI), size(x)...)
end
# 1.044 ms (40 allocations: 617.20 KiB)