Unable to select last element with range indexing

I would like to access subsets of an array using range indexing. However, I can’t figure out how to select a subset of the array that includes the last element. Here’s a simple example to illustrate.

// stan-indexing-debug.stan
data {
    int n, start, end;
    int x[n];
}

generated quantities {
    int y[end - start] = x[start:end];
}

Running the program with cmdstanpy produces expected results if I don’t want to select the last element. For example,

import cmdstanpy
import numpy as np


model = cmdstanpy.CmdStanModel(stan_file="stan-indexing-debug.stan")
n = 5
data = {"n": n, "x": 1 + np.arange(n), "start": 2, "end": 4}
fit = model.sample(data, iter_sampling=1, iter_warmup=0, fixed_param=True)
fit.stan_variable("y")  # array([[2., 3.]])

Setting end = n gives me all but the last element:

data = {"n": n, "x": 1 + np.arange(n), "start": 2, "end": n}
fit = model.sample(data, iter_sampling=1, iter_warmup=0, fixed_param=True)
fit.stan_variable("y")  # array([[2., 3., 4.]])

I expected that setting end = n + 1 would also give me the last element, but it raises an error.

data = {"n": n, "x": 1 + np.arange(n), "start": 2, "end": n + 1}
fit = model.sample(data, iter_sampling=1, iter_warmup=0, fixed_param=True)
fit.stan_variable("y")
# Exception: array[..., ...] index: accessing element out of range. index 6 out of range; expecting index to be between 1 and 5

How can I use range indexing that includes the last index?

For reference, here’s my setup information from cmdstanpy.show_versions().

INSTALLED VERSIONS
---------------------
python: 3.9.2 (default, Mar 25 2021, 12:34:08) 
[Clang 12.0.0 (clang-1200.0.32.29)]
python-bits: 64
OS: Darwin
OS-release: 21.6.0
machine: arm64
processor: arm
byteorder: little
LC_ALL: None
LANG: None
LOCALE: (None, 'UTF-8')
cmdstan_folder: /Users/till/.cmdstan/cmdstan-2.28.2
cmdstan: (2, 28)
cmdstanpy: 1.0.4
pandas: 1.4.3
xarray: None
tdqm: None
numpy: 1.21.2
ujson: 5.1.0

Thank you for the help!

The length of y is set incorrectly. It should be end - start + 1.

That’s it, thank you! Setting the length of y incorrectly lead me to believe that indexing was exclusive on the upper end like in numpy.