6

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?

0

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Interesting - it seems to be valid syntax because you could do: X = Float64; X[1 5 9]. And error is not from parsing but just about typed_hcat(T, ...) missing. But I am not able to define appropriate typed_hcat function! Why?
that's because typed_hcat is for what I showed up there: the first argument should be a data type that is the element-type for the resulting array. I believe this is built into the core Julia since it's special parsing and handling for array construction.
@Liso: try Base.typed_hcat(::AbstractArray, ::Int...) = "Don't do this!".
What I find interesting is that (1:10)[[1 4]] and (1:10)[[1, 4]].' result in different types. I wonder if there's a valid reason for this, or just a historical remnant of how the two were developed so far.
You lost dimension with (1:10)[[1, 4]]. Try this (1:10)[[1, 4],:] or this (1:10)[[1, 4],:].' (or reshape((1:10)[[1, 4]], (2,1)) )
3

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]]

1 Comment

As long as you understand that X[2:4, :][[1 3],[1 3]] returns 4 elements rather than 2 (which might be what you expect if you're coming from python).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.