How to index a Julia array

Viewed 7010

I am having trouble understanding what seems like an inconsistent behavior in Julia.

X = reshape(1:100, 10, 10)
b = [1 5 9]
X[2, :][b] # returns the correct array
X[2, :][1 5 9] # throws an error

Can someone explain why using the variable b works to index an array but not when I write the index myself?

2 Answers

Since x = X[2,:] is just a vector, we can simplify the example to just talking about indexing behavior on vectors.

x[v] where v is a collection of integers returns the subset of x. Thus x[(1,5,9)], or x[[1,5,9]] is thus using that getindex(x::Vector,i::AbstractArray) dispatch.

Note that x[[1 5 9]] works because v = [1 5 9] makes v a row vector. That's valid syntax, but x[1 5 9] just isn't even valid Julia syntax. That syntax means something else:

v = Float64[1 5 9]

returns a row vector with element type Float64.

I have figured out a solution.

Rather than write X[2, :][1 5 9] I should have written x[2, :][[1 5 9]]

I believe this makes sense when we imagine indexing on two dimensions the second time. This makes it possible to write more complicate indices, like X[2:4, :][[1 3],[1 3]]

Related