Skip to content

Commit

Permalink
Merge pull request JuliaLang#4764 from magistere/master
Browse files Browse the repository at this point in the history
Implement logical indexing for SubArray. Fixes JuliaLang#4763
  • Loading branch information
timholy committed Nov 18, 2013
2 parents 7897b0f + ceed2fa commit 30fb816
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
19 changes: 19 additions & 0 deletions base/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,25 @@ function getindex(s::SubArray, is::Integer...)
s.parent[index]
end

function getindex_bool_1d(S::SubArray, I::AbstractArray{Bool})
n = sum(I)
out = similar(S, n)
c = 1
for i = 1:length(I)
if I[i]
out[c] = S[i]
c += 1
end
end
out
end

getindex{T}(S::SubArray{T,1}, I::AbstractArray{Bool,1}) = getindex_bool_1d(S, I)
getindex{T}(S::SubArray{T,2}, I::AbstractArray{Bool,2}) = getindex_bool_1d(S, I)
getindex{T}(S::SubArray{T,3}, I::AbstractArray{Bool,3}) = getindex_bool_1d(S, I)
getindex{T}(S::SubArray{T,4}, I::AbstractArray{Bool,4}) = getindex_bool_1d(S, I)
getindex{T}(S::SubArray{T,5}, I::AbstractArray{Bool,5}) = getindex_bool_1d(S, I)

getindex{T}(s::SubArray{T,1}, I::Range1{Int}) =
getindex(s.parent, (s.first_index+(first(I)-1)*s.strides[1]):s.strides[1]:(s.first_index+(last(I)-1)*s.strides[1]))

Expand Down
7 changes: 7 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@ sA = sub(A, 1:2:3, 1:3:5, 1:2:8)
@test strides(sA) == (2,9,30)
@test sA[:] == A[1:2:3, 1:3:5, 1:2:8][:]

# sub logical indexing #4763
A = sub([1:10], 5:8)
@test A[A.<7] == [5, 6]
B = reshape(1:16, 4, 4)
sB = sub(B, 2:3, 2:3)
@test sB[sB.>8] == [10, 11]

# slice
A = reshape(1:120, 3, 5, 8)
sA = slice(A, 2, :, 1:8)
Expand Down

0 comments on commit 30fb816

Please sign in to comment.