I wonder if this is important enough to warrant an operator. Something like
v[i%%n]?


On Mon, Apr 28, 2014 at 6:53 AM, Tim Holy <[email protected]> wrote:

> There's mod1, if that helps.
>
> --Tim
>
> On Monday, April 28, 2014 02:57:09 AM Tomas Lycken wrote:
> > In languages with zero-indexed vectors, I can easily let my indices
> "wrap"
> > by taking a modulus:
> >
> > N = length(v)
> > for i = 0:N-1
> >     v[i+1 % N] = ...
> > end
> >
> > will loop from the second element to the last, and then take the first,
> > since N % N == 0. However, with Julia's 1-indexed arrays, it's not that
> > easy - at some point, I'll end up at index 0:
> >
> > N = length(v)
> > for i = 1:N
> >     v[i + 1 % N] = ... # breaks at i = N-1, since index then becomes 0
> > end
> >
> > I could first offset my entire loop index by one, take the modulus, and
> > then add one again:
> >
> > N = length(v)
> > for i = 0:N-1
> >     v[(i+1 % N) + 1] = ...
> > end
> >
> > but this seems clunky to me, and is difficult to understand at first
> glance
> > (maybe not to current me, but to me-in-a-month trying to figure out what
> > this code does...). Is there a more idiomatic way to do the same thing in
> > Julia?
> >
> > My actual problem is having a (sorted) list of vertices in a polygon, and
> > wanting to loop over the edges (i.e. adjacent pairs in the list), so in
> > each step I want to access something like v[i+1]-v[i] and have the
> > end-points close the loop.
> >
> > Thanks in advance,
> >
> > // T
>

Reply via email to