Skip to content

Commit

Permalink
Add size(::LinearIndices) (#455)
Browse files Browse the repository at this point in the history
* Add size(::LinearIndices)

Fixes indexing LinearIndices with an array. This is useful in particular
to convert cartesian indices that find() now returns to linear indices.

* Add size(::LinearIndices) on older 0.7 versions
  • Loading branch information
nalimilan authored and ararslan committed Feb 6, 2018
1 parent b2aac2e commit 8cca897
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1376,12 +1376,15 @@ end
# AbstractArray implementation
Base.IndexStyle(::Type{LinearIndices{N,R}}) where {N,R} = IndexCartesian()
Compat.axes(iter::LinearIndices{N,R}) where {N,R} = iter.indices
Base.size(iter::LinearIndices{N,R}) where {N,R} = length.(iter.indices)
@inline function Base.getindex(iter::LinearIndices{N,R}, I::Vararg{Int, N}) where {N,R}
dims = length.(iter.indices)
#without the inbounds, this is slower than Base._sub2ind(iter.indices, I...)
@inbounds result = reshape(1:prod(dims), dims)[(I .- first.(iter.indices) .+ 1)...]
return result
end
elseif VERSION < v"0.7.0-DEV.3395"
Base.size(iter::LinearIndices{N,R}) where {N,R} = length.(iter.indices)
end

@static if !isdefined(Base, Symbol("@info"))
Expand Down
3 changes: 2 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1198,12 +1198,13 @@ let c = CartesianIndices(1:3, 1:2), l = LinearIndices(1:3, 1:2)
@test first(c) == CartesianIndex(1, 1)
@test CartesianIndex(1, 1) in c
@test first(l) == 1
@test size(c) == (3, 2)
@test size(c) == size(l) == (3, 2)
@test c == collect(c) == [CartesianIndex(1, 1) CartesianIndex(1, 2)
CartesianIndex(2, 1) CartesianIndex(2, 2)
CartesianIndex(3, 1) CartesianIndex(3, 2)]
@test l == collect(l) == reshape(1:6, 3, 2)
@test c[1:6] == vec(c)
@test l[1:6] == vec(l)
@test l == l[c] == map(i -> l[i], c)
@test l[vec(c)] == collect(1:6)
@test CartesianIndex(1, 1) in CartesianIndices((3, 4))
Expand Down

0 comments on commit 8cca897

Please sign in to comment.