2

I'm new to Julia and wonder what is the best way to get the index of subarray, consider the following array of vectors

vec = [[1, 2, 3], [4, 5, 6]]

I would like to get the index of the element [4, 5, 6], however I can not use getindex(), execution of the following code:

getindex(vec, [1, 2, 3])

gives:

BoundsError: attempt to access 2-element Array{Array{Int64,1},1} at index [[1, 2, 3]]

So I wonder if there are any effective build-in methods for doing this. Of course I can map this array of vectors into another array of numbers and do a search inside new array of numbers, but it isn't really a solution what I expect.

Second question is how do I learn more about search methods in Julia and their performances. I guess the theoretical speed of search scales like \sqrt(N) however depending on the certain method the real code time may vary significantly.

2 Answers 2

4

Judging by the name of the function you might be mislead: getindex retrieves the value stored at an index.

If you want to find the index of something in an array you can make use of find* methods findfirst, findall...

julia> vec=[[1,2,3],[4,5,6]]
2-element Array{Array{Int64,1},1}:
 [1, 2, 3]
 [4, 5, 6]

julia> i = findfirst(x->x==[4,5,6],vec)
2

julia> vec[i]
3-element Array{Int64,1}:
 4
 5
 6

Concerning your second question:

It's best to inform yourself about search/sort algorithms in general (e.g. https://codeburst.io/algorithms-i-searching-and-sorting-algorithms-56497dbaef20?gi=3bdbf8cbaca0), because the performance depends much more on the chosen algorithm than on the language specific implementation. E.g. time complexity can be very different (O(n), O(log(n),...).

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

1 Comment

Our identical answers cross-posted :-)
4

I think you've misunderstood what getindex does. It's the function that gets called by [], so

julia> getindex(vec, 2)
3-element Array{Int64,1}:
 4
 5
 6

All search (or "find") methods in Julia take a function as it's first argument, and find where the function evaluates to true. To find a particular element, use isequal or == (they are equivalent):

julia> findall(==([1,2,3]), vec)
1-element Array{Int64,1}:
 1

Comments

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.