Exactly what I was hoping for. Thanks a lot! // T
On Monday, April 28, 2014 12:29:58 PM UTC+2, Mikael Simberg wrote: > > There's the function mod1 which does exactly the shifting by 1 that you > need. > > > On Mon, Apr 28, 2014, at 3:22, Tomas Lycken wrote: > > ...and of course my Julia example didn't really work out. Because of > operator precedence, I actually need v[((i+1) % (N-1)) + 1] in the last > example, making the need for a better idiom for this kind of looping even > greater. My eyes are bleeding... > > // T > > On Monday, April 28, 2014 11:57:09 AM UTC+2, 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 > > > >
