Best way to drop an entry of a CartesianIndex?

Out of curiosity, what is the best way to drop one entry of an idx::CartesianIndex? Or, generally, to access a slice of it. It’s forbidden to do idx[2:5], so right now I’m doing:


Just curious if this is the best way to do this.

That works. You can also do the following which may be slightly shorter.

julia> idx = CartesianIndex((1,2,3,4,5))
CartesianIndex(1, 2, 3, 4, 5)

julia> CartesianIndex(idx.I[2:5])
CartesianIndex(2, 3, 4, 5)

Your version is arguably better though as it does not depend on the implementation details of CartesianIndex.

A better answer might come if you tell us what larger problem you are trying to solve.

1 Like

Thanks! This definitely works for me, as much as I’m tempted to overload Base.getindex and introduce all kinds of weird bugs into my project.

My particular problem is just that I have a a::Array{Float64, 5} and I want to get the whole “column” containing a particular index idx::CartesianIndex{5}.

So basically, right now I’m doing

function get_column_containing(A, idx)
  return A[:, CartesianIndex(Tuple(idx)[2:5])

There is also:


which may be a little more self documenting.

You may also find Base.setindex (not to be confused with the more popular Base.setindex!) to be useful, since stripping/replacing things in the middle (if you have that need) can be more tedious.

julia> idx = CartesianIndex(1,2,3,4,5);

julia> Base.setindex(Tuple(idx),:,2)
(1, Colon(), 3, 4, 5)

julia> A[Base.setindex(Tuple(idx),:,2)...]

Note that this call to setindex is technically type-unstable, but if the index is a compile time constant then it will usually resolve itself via constant propagation (compare @code_warntype Base.setindex(Tuple(idx),:,2) to @code_warntype (i->Base.setindex(Tuple(i),:,2))(idx)). The same thing appears to happen with CartesianIndex(Tuple(idx)[2:5]), where the 2:5 would normally cause a type instability (length(2:5) is not a part of the type of 2:5, but length is important to Tuple) but is resolved via constant propagation.