Skip to content

How to iterate over the non-zero values of a sparse array

An answer to this question on Stack Overflow.

Question

I have a sparse array in Julia and would like to iterate over its non-zero entries. What's a good way of doing this?

So far, I have:

using SparseArrays
a = sprandn(20,20,0.3)
for (x,y,v) in a
  print(x,y,v)
end

Answer

The findnz function returns a tuple containing arrays of the x, y, and value components of the sparse matrix. That is,

findnz(a) gives ([x1, x2, x3, ...], [y1, y2, y3, ...], [v1, v2, v3, ...])

You can use this like an iterator as follows:

for (x,y,v) in zip(findnz(a)...)
  println(x,' ',y,' ',v)
end