From 8cca897ff1bf251bc2fb6e806ec481cfc478de26 Mon Sep 17 00:00:00 2001 From: Milan Bouchet-Valat Date: Tue, 6 Feb 2018 04:13:47 +0100 Subject: [PATCH] Add size(::LinearIndices) (#455) * 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 --- src/Compat.jl | 3 +++ test/runtests.jl | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Compat.jl b/src/Compat.jl index b6b8ae8c54596..14a450ed51a22 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -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")) diff --git a/test/runtests.jl b/test/runtests.jl index 8a5e5c2238fe7..afa75c929e4bc 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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))