Skip to content

Commit

Permalink
add linear indexing with single multi-dimensional index. closes #2247
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson committed Apr 3, 2013
1 parent 4a93e3a commit b8e41d1
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 3 deletions.
9 changes: 9 additions & 0 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,15 @@ end

getindex(t::AbstractArray, i::Real) = error("indexing not defined for ", typeof(t))

# linear indexing with a single multi-dimensional index
function getindex(A::AbstractArray, I::AbstractArray)
x = similar(A, size(I))
for i=1:length(I)
x[i] = A[I[i]]
end
return x
end

# index A[:,:,...,i,:,:,...] where "i" is in dimension "d"
# TODO: more optimized special cases
slicedim(A::AbstractArray, d::Integer, i) =
Expand Down
2 changes: 1 addition & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ end
# Multidimensional indexing
let getindex_cache = nothing
global getindex
function getindex(A::Array, I::Union(Real,AbstractArray)...)
function getindex(A::Array, I::Union(Real,AbstractVector)...)
check_bounds(A, I...)
I = indices(I)
X = similar(A, index_shape(I...))
Expand Down
2 changes: 1 addition & 1 deletion base/bitarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ end

let getindex_cache = nothing
global getindex
function getindex(B::BitArray, I::Union(Real,AbstractArray)...)
function getindex(B::BitArray, I::Union(Real,AbstractVector)...)
I = indices(I)
X = BitArray(index_shape(I...))
Xc = X.chunks
Expand Down
2 changes: 1 addition & 1 deletion base/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ function parentdims(s::SubArray)
dimindex
end

function getindex(s::SubArray, I::Union(Real,AbstractArray)...)
function getindex(s::SubArray, I::Union(Real,AbstractVector)...)
newindexes = translate_indexes(s, I...)

rs = index_shape(I...)
Expand Down
11 changes: 11 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -387,3 +387,14 @@ begin
@test vec(S[i,:]) == sort(vec(a[i,:]))
end
end

# single multidimensional index
let
a = rand(6,6)
I = [1 4 5; 4 2 6; 5 6 3]
a2 = a[I]
@test size(a2) == size(I)
for i = 1:length(a2)
@test a2[i] == a[I[i]]
end
end

0 comments on commit b8e41d1

Please sign in to comment.