9

I'd like to access elements in an array in a circular manner. Normally a modulo suffices but in Julia arrays start at 1. At the moment I'm basically converting the indices to a 0-based index and back. But this doesn't work for negative indices.

A = 1:5
for i in -6:6
    println(i, " -> ", ((i - 1) % length(A)) + 1)
end

Output

-6 -> -1 # wrong
-5 ->  0 # wrong
-4 ->  1 # wrong
-3 -> -3 # wrong
-2 -> -2 # wrong
-1 -> -1 # wrong
 0 ->  0 # wrong
 1 ->  1
 2 ->  2
 3 ->  3
 4 ->  4
 5 ->  5
 6 ->  1

2 Answers 2

16

I usually use mod1 function for this. Here is an example:

julia> [-10:10 mod1.(-10:10, 5)]
21×2 Array{Int64,2}:
 -10  5
  -9  1
  -8  2
  -7  3
  -6  4
  -5  5
  -4  1
  -3  2
  -2  3
  -1  4
   0  5
   1  1
   2  2
   3  3
   4  4
   5  5
   6  1
   7  2
   8  3
   9  4
  10  5
Sign up to request clarification or add additional context in comments.

Comments

3

The % operator is not the mod operator as you suspect, but the rem operator.

Replace your modulus operation with mod( i-1, length(A) ) and you will get your intended result.


PS. I would have to add, the use-case for such circularity also matters. If you're trying to replicate python-like negative indices, where a negative index of -1 indexes the last element of the array, and continuing circularly in that fashion from that point on for negative numbers, would necessarily require a different treatment for 0 and two different branches, one for positive and one for negative numbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.