Acess an array using another array

I want to be able to acces a multi-dimentional array using another array. This is what happens if I try to do it:

x = [1,1,1]
y = zeros(Int64,(3,3,3)) # 3D array
println(y[x]) # Prints [0,0,0]
println(y[1,1,1]) # Prints 0

println(y[x]) isn’t printing 0, why?

Thanks!

With x = [1,1,1] writing y[x] is the same as writing y[[1,1,1]]. This takes 3 times the same value from y: it considers the 3D array as a 1D array and takes the first value (three times). On the other hand, writing y[1,1,1] takes one time the value at position (1,1,1) (which is also the first value).

To do the equivalent of y[1,1,1] with x as index you can use the splatting operator ... as in y[x...].

3 Likes

Julia has a dedicated type for multidimensional indices. It will behave the way you’re hoping.

x = CartesianIndex(1,1,1)
println(y[x])

CartesianIndex behaves like a single index (rather than array), which is why it returns a single value. This is preferred (syntactically, stylistically, and performance-wise) to splatting arrays as indices (e.g., y[[1,1,1]...]).

To elaborate on the previous reply, your initial attempt to index an array y with an array x that has N values will return an array with N values, where each entry in x selects which entry in y appears in those N positions. Hence y[[1,1,1]] returns the [y[1],y[1],y[1]]. When multidimensional arrays are indexed with single indices like y[1], they use “linear indexing”. See reshape(1:12,3,4) for an example of what this looks like.

4 Likes

Thanks!

Splatting alocates a lot of memory, your solution is more performant.