Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of an item in a Vector in Julia

Tags:

julia

If I have a Vector of Strings such as: ["big", "friendly", "giant"], how can I get the index of "friendly" (2)?

like image 872
DVNold Avatar asked Oct 20 '25 14:10

DVNold


1 Answers

You can use the findfirst function (and its friends findlast, findnext, findprev and findall) for problems like this.

julia> x = ["big", "friendly", "giant"]
julia> findfirst(item -> item == "friendly", x)
2

This uses an anonymous function item -> item == "friendly" which tests each item in the array. If the function returns true the index of that item is returned. You can write it slightly more concisely as

julia> findfirst(==("friendly"), x)
2

If the item isn't found, nothing is returned.

like image 157
htl Avatar answered Oct 22 '25 03:10

htl