# Creating a sparse matrix from find operation on dense matrix

**URL:** <https://discourse.julialang.org/t/creating-a-sparse-matrix-from-find-operation-on-dense-matrix/61056>\
**Category:** General Usage\
**Tags:** question, sparse\
**Created:** [May 13, 2021, 1:19am UTC](https://discourse.julialang.org/t/creating-a-sparse-matrix-from-find-operation-on-dense-matrix/61056 "2021-05-13T01:19:28Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![bmit](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bmit/32/12443_2.png) [@bmit](https://discourse.julialang.org/u/bmit)\
**Post date:** [May 13, 2021, 1:55am UTC](https://discourse.julialang.org/t/creating-a-sparse-matrix-from-find-operation-on-dense-matrix/61056/3 "2021-05-13T01:55:39Z")

</div>

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](https://discourse.julialang.org/t/cartesian-indices-linear-indices-and-sparse-matrices/13781).

```julia
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)

```

---

_[View the full topic](https://discourse.julialang.org/t/creating-a-sparse-matrix-from-find-operation-on-dense-matrix/61056)._
