From 6f1ad9c11cb8d91f1f1ac0cae8d03f532ba54b62 Mon Sep 17 00:00:00 2001 From: Tim Holy Date: Mon, 15 Aug 2016 15:37:31 -0500 Subject: [PATCH] Make `find` indices-aware --- base/array.jl | 8 ++++++-- test/offsetarray.jl | 5 +++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/base/array.jl b/base/array.jl index da83d1faa0b80..2e0f5b4feb98b 100644 --- a/base/array.jl +++ b/base/array.jl @@ -1077,15 +1077,18 @@ function find(testf::Function, A) # use a dynamic-length array to store the indexes, then copy to a non-padded # array for the return tmpI = Array{Int,1}(0) + inds = _index_remapper(A) for (i,a) = enumerate(A) if testf(a) - push!(tmpI, i) + push!(tmpI, inds[i]) end end I = Array{Int,1}(length(tmpI)) copy!(I, tmpI) return I end +_index_remapper(A::AbstractArray) = linearindices(A) +_index_remapper(iter) = Colon() # safe for objects that don't implement length """ find(A) @@ -1110,9 +1113,10 @@ function find(A) nnzA = countnz(A) I = Vector{Int}(nnzA) count = 1 + inds = _index_remapper(A) for (i,a) in enumerate(A) if a != 0 - I[count] = i + I[count] = inds[i] count += 1 end end diff --git a/test/offsetarray.jl b/test/offsetarray.jl index 7731895896f91..a8ce0835895ee 100644 --- a/test/offsetarray.jl +++ b/test/offsetarray.jl @@ -281,6 +281,11 @@ I,J,N = findnz(z) @test I == [-1] @test J == [0] @test N == [2] +h = OffsetArray([-1,1,-2,2,0], (-3,)) +@test find(h) == [-2:1;] +@test find(x->x>0, h) == [-1,1] +@test find(x->x<0, h) == [-2,0] +@test find(x->x==0, h) == [2] v = OffsetArray([1,1e100,1,-1e100], (-3,))*1000 v2 = OffsetArray([1,-1e100,1,1e100], (5,))*1000