Slicing in Stan using double colon

Hi all,

I am looking at the documentation about slicing and was wondering if its possible to only specify step. In Python this is possible using the double colon:

array[::step] 

Basically, I want to recreate the below in Stan:

n = 11
m = 2

sequence = [0] * n
sequence[::2 * m] = [1] * len(sequence[::2 * m])
sequence[1::2 * m] = [1] * len(sequence[1::2 * m])

print(sequence)
# [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0]

I started with using zeros_int_array but how to proceed from there?

Anyone?

There is no direct shorthand for this in Stan.

You can accomplish something similar using the linspaced_int_array function

@WardBrian I played unsuccessfully around with that. How would your implementation looks like?

I think this would work:

array[] int range(int start, int stop, int step){
    int n = (stop - start + 1) %/% step;
    return linspaced_int_array(n, start, stop);
}

I might have an off-by-one error in there.

This ended up being more subtle than I thought but I believe this works:

  array[] int range(int start, int stop, int step) {
    if (start > stop) {
      int n = (start - stop) %/% -step;
      int begin = n * step + start;
      return reverse(linspaced_int_array(n + 1, begin, start));
    }
    int n = (stop - start) %/% step;
    int end = n * step + start;
    return linspaced_int_array(n + 1, start, end);
  }

Note that the result is inclusive on both ends, such that range(0,10,2) == {0, 2, 4, 6, 8, 10}

2 Likes