Skip to content

Commit

Permalink
Define find and findnz for SparseVector (#18049)
Browse files Browse the repository at this point in the history
  • Loading branch information
pranavtbhat authored and ViralBShah committed Aug 16, 2016
1 parent 82dcfc7 commit bf2c29f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
51 changes: 50 additions & 1 deletion base/sparse/sparsevector.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

### Common definitions

import Base: scalarmax, scalarmin, sort
import Base: scalarmax, scalarmin, sort, find, findnz

### The SparseVector

Expand Down Expand Up @@ -560,6 +560,55 @@ function getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractVector)
SparseVector(n, rowvalB, nzvalB)
end

function find{Tv,Ti}(x::SparseVector{Tv,Ti})
numnz = nnz(x)
I = Array(Ti, numnz)

nzind = x.nzind
nzval = x.nzval

count = 1
@inbounds for i = 1 : numnz
if nzval[i] != 0
I[count] = nzind[i]
count += 1
end
end

count -= 1
if numnz != count
deleteat!(I, (count+1):numnz)
end

return I
end

function findnz{Tv,Ti}(x::SparseVector{Tv,Ti})
numnz = nnz(x)

I = Array(Ti, numnz)
V = Array(Tv, numnz)

nzind = x.nzind
nzval = x.nzval

count = 1
@inbounds for i = 1 : numnz
if nzval[i] != 0
I[count] = nzind[i]
V[count] = nzval[i]
count += 1
end
end

count -= 1
if numnz != count
deleteat!(I, (count+1):numnz)
deleteat!(V, (count+1):numnz)
end

return (I, V)
end

### Generic functions operating on AbstractSparseVector

Expand Down
7 changes: 7 additions & 0 deletions test/sparsedir/sparsevector.jl
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,13 @@ let x = SparseVector(10, [2, 7, 9], [2.0, 7.0, 9.0])
@test Base.SparseArrays.dropstored!(x, 5) == SparseVector(10, [7, 9], [7.0, 9.0])
end

# find and findnz tests
@test find(spv_x1) == find(x1_full)
@test findnz(spv_x1) == (find(x1_full), filter(x->x!=0, x1_full))
let xc = SparseVector(8, [2, 3, 5], [1.25, 0, -0.75]), fc = full(xc)
@test find(xc) == find(fc)
@test findnz(xc) == ([2, 5], [1.25, -0.75])
end

### Array manipulation

Expand Down

0 comments on commit bf2c29f

Please sign in to comment.