Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 742
Richard Avatar asked Oct 02 '18 07:10

Richard


2 Answers

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
like image 77
Richard Avatar answered Oct 29 '22 04:10

Richard


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
like image 38
Kristoffer Carlsson Avatar answered Oct 29 '22 05:10

Kristoffer Carlsson