Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of subarray in Julia

Tags:

julia

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.

like image 580
ns1gn Avatar asked Dec 07 '25 08:12

ns1gn


2 Answers

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),...).

like image 53
laborg Avatar answered Dec 09 '25 17:12

laborg


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
like image 33
Michael K. Borregaard Avatar answered Dec 09 '25 17:12

Michael K. Borregaard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!