How to increment CartesianIndex?

Hello!

I think I am just not finding the right command, but how to increment a CartesianIndex? I have a matrix of size 5x5. Suppose I have a cartesian index of CartesianIndex(3,1) how to increment it to CartesianIndex(4,1) based on the information of matrix size?

Kind regards

julia> CartesianIndex(3,1)+CartesianIndex(1,0)
CartesianIndex(4, 1)
2 Likes

Depends on what you mean by “increment”, but you can also use nextind to get the next (consecutive) index in a given array:

julia> A = rand(5,5);

julia> nextind(A, CartesianIndex(3,1))
CartesianIndex(4, 1)

(Better documentation for this was recently merged: Document the generic functions nextind() and prevind() by JamesWrigley · Pull Request #52658 · JuliaLang/julia · GitHub)

5 Likes

That is extremely close to what I want. I notice that it does not error out though:

julia> A = zeros(5,5)
5Ă—5 Matrix{Float64}:
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0

julia> nextind(A, CartesianIndex(4,1))
CartesianIndex(5, 1)

julia> nextind(A, CartesianIndex(4,1))
CartesianIndex(5, 1)

julia> nextind(A, CartesianIndex(5,5))
CartesianIndex(1, 6)

julia> nextind(A, CartesianIndex(5,6))
CartesianIndex(1, 7)

julia> nextind(A, CartesianIndex(5,7))
CartesianIndex(1, 8)

I would like it to throw nothing or return the same value when doing 5,5 since it is last element.

Kind regards

Then you can use iterate with CartesianIndices(A):

julia> I = CartesianIndices(A)
CartesianIndices((5, 5))

julia> iterate(I, CartesianIndex(4,1))
(CartesianIndex(5, 1), CartesianIndex(5, 1))

julia> iterate(I, CartesianIndex(5,4))
(CartesianIndex(1, 5), CartesianIndex(1, 5))

julia> iterate(I, CartesianIndex(4,5))
(CartesianIndex(5, 5), CartesianIndex(5, 5))

julia> iterate(I, CartesianIndex(5,5))  # last index, returns nothing

(When it doesn’t return nothing, it returns the same index twice due to the iterate API, but you can just ignore the second return value and the compiler should eliminate it.)

5 Likes