Periodic or cyclic arrays possible?

157 views
Skip to first unread message

Ferran Mazzanti

unread,
Feb 6, 2016, 7:08:03 PM2/6/16
to julia-users
Hi folks,

I was wondering if it is possible to use in a simple way cyclic arrays in Julia? What I'm after is sometbing that understands that the next element in a[] after end is a[1], so a[end+1]=a[1], a[end+2]=a[2] etc... I know I can index the array with the remainder operator % to achieve this same result, but I wonder if one can declare the array directly in one way or another to achieve this directly.

Thanks in advance,

Ferran.

Cedric St-Jean

unread,
Feb 6, 2016, 8:40:17 PM2/6/16
to julia-users
You can define our own datatype to do this. It's one of the most fundamental tasks in Julia!

immutable CircularArray{T}
    arr
::Vector{T}
end

Base.getindex(ca::CircularArray, i) = ca.arr[(i-1) % length(ca.arr) + 1]
Base.setindex(...) = ...
...

a
= CircularArray([1,2,3])
a
[14] # yields 2

Cédric

Erik Schnetter

unread,
Feb 7, 2016, 10:52:45 AM2/7/16
to julia...@googlegroups.com
The expression `(i-1) % length + 1` is not correct for negative `i`.
You have to use `mod` instead of `%`.

Julia has a function `mod1(x,y)` that is essentially defined as
`mod(x-1, y) +1`, so that's what you probably want to use.

-erik
--
Erik Schnetter <schn...@gmail.com>
http://www.perimeterinstitute.ca/personal/eschnetter/

Matt Bauman

unread,
Feb 7, 2016, 5:46:35 PM2/7/16
to julia-users
I highly recommend reading the Interfaces chapter[1] for a walk-through on creating your own array type.  Another great trick that you can use is `A[mod1(x, end)]`.

Reply all
Reply to author
Forward
0 new messages