Subranges of general indexes

This comes from a more general problem, but for an MWE, consider a function that returns the indices of a vector where one element is not equal to the previous one. I want it to work for general indexes, so I wrote it as

function jumpindexes(v::AbstractVector)
    xprev = first(v)
    ι = LinearIndices(v)
    j = similar(ι, 0)
    for i in ι[2:end] # PROBLEM HERE
        x = v[i]
        x == xprev || push!(j, i)
        xprev = x
    end
    j
end

but

julia> using OffsetArrays

julia> v = [1, 1, 2, 2, 2, 3, 3, 4]
8-element Array{Int64,1}:
 1
 1
 2
 2
 2
 3
 3
 4

julia> o = OffsetArray(v, -4:3)
OffsetArray(::Array{Int64,1}, -4:3) with eltype Int64 with indices -4:3:
 1
 1
 2
 2
 2
 3
 3
 4

julia> jumpindexes(v)
3-element Array{Int64,1}:
 3
 6
 8

julia> jumpindexes(o)                  # wrong, drops negative indexes
2-element Array{Int64,1}:
 2
 3

The problem basically boils down to

LinearIndices(o)[2:end]

How can I implement this algorithm with general indexing?

In general, how can I take subranges for general indexes?

(edit: on v0.7)

I’d use Iterators.drop(ι, 1) — I think that’d be just as efficient. Hopefully in 1.0 you’ll be able to use ι[begin+1:end].

1 Like