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
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
Here is a direct way to do it
using SparseArrays
function print_nz(A)
for col in 1:size(A, 2)
for r in nzrange(A, col)
println(rowvals(A)[r], ' ', col, ' ', nonzeros(A)[r])
end
end
end
and an example of it being used:
julia> A = [1 2 1
0 0 1
3 0 0];
julia> print_nz(sparse(A))
1 1 1
3 1 3
1 2 2
1 3 1
2 3 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With