Skip to content

Commit b8e41d1

Browse files
committed
add linear indexing with single multi-dimensional index. closes #2247
1 parent 4a93e3a commit b8e41d1

File tree

5 files changed

+23
-3
lines changed

5 files changed

+23
-3
lines changed

base/abstractarray.jl

+9
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,15 @@ end
465465

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

468+
# linear indexing with a single multi-dimensional index
469+
function getindex(A::AbstractArray, I::AbstractArray)
470+
x = similar(A, size(I))
471+
for i=1:length(I)
472+
x[i] = A[I[i]]
473+
end
474+
return x
475+
end
476+
468477
# index A[:,:,...,i,:,:,...] where "i" is in dimension "d"
469478
# TODO: more optimized special cases
470479
slicedim(A::AbstractArray, d::Integer, i) =

base/array.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ end
327327
# Multidimensional indexing
328328
let getindex_cache = nothing
329329
global getindex
330-
function getindex(A::Array, I::Union(Real,AbstractArray)...)
330+
function getindex(A::Array, I::Union(Real,AbstractVector)...)
331331
check_bounds(A, I...)
332332
I = indices(I)
333333
X = similar(A, index_shape(I...))

base/bitarray.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ end
372372

373373
let getindex_cache = nothing
374374
global getindex
375-
function getindex(B::BitArray, I::Union(Real,AbstractArray)...)
375+
function getindex(B::BitArray, I::Union(Real,AbstractVector)...)
376376
I = indices(I)
377377
X = BitArray(index_shape(I...))
378378
Xc = X.chunks

base/subarray.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ function parentdims(s::SubArray)
244244
dimindex
245245
end
246246

247-
function getindex(s::SubArray, I::Union(Real,AbstractArray)...)
247+
function getindex(s::SubArray, I::Union(Real,AbstractVector)...)
248248
newindexes = translate_indexes(s, I...)
249249

250250
rs = index_shape(I...)

test/arrayops.jl

+11
Original file line numberDiff line numberDiff line change
@@ -387,3 +387,14 @@ begin
387387
@test vec(S[i,:]) == sort(vec(a[i,:]))
388388
end
389389
end
390+
391+
# single multidimensional index
392+
let
393+
a = rand(6,6)
394+
I = [1 4 5; 4 2 6; 5 6 3]
395+
a2 = a[I]
396+
@test size(a2) == size(I)
397+
for i = 1:length(a2)
398+
@test a2[i] == a[I[i]]
399+
end
400+
end

0 commit comments

Comments
 (0)