Question about Indexing with CartesianIndex

Let’s say you have an array a = reshape(1:5*10*25, 5, 10, 25). Why does all(a[CartesianIndex(1, 1), 1:end] .== a[CartesianIndex(1, 1), 1:10] .== a[1, 1, 1:10]) return true? I would expect that a[CartesianIndex(1, 1), 1:end] would return a vector of length 25 like a[1, 1, 1:end]. What is the reasoning behind this? It’s almost as if the end is picking up on the length of the second dimension when one would expect it to pick up on the length of the third dimension.

Edit: I just saw the big warning in the docs. Sort of wish this just threw an error instead of letting bugs happen, but it is what it is.

Yup, that’s the answer. Unfortunately, the end calculation is based entirely upon how many ,-separated elements there are in the []… and it happens at the parser level before we have any type information. It’s even trickier than it appears since we also support arrays of CartesianIndex, too.

We’ve considered a redesign that would allow us to do this better, but it’s not obviously a win, either. Sorry this caught you out. I hate traps like this and wish we could do better.

1 Like