Reputation: 34530
What is the simplest way to find the first index of some item in an array in Julia?
Upvotes: 25
Views: 22074
Reputation: 3025
You can use findfirst
as follows:
A = [1, 4, 2, 3, 2]
function myCondition(y)
return 2 == y
end
println( findfirst(myCondition, A) )
# output: 3
you can read more in this Link
Upvotes: 8
Reputation: 12179
There is findfirst
and more generally findnext
, which allows you to restart where you left off. One advantage of these two is that you don't need to allocate an output array, so the performance will be better (if you care).
Also, keep in mind that (unlike some other languages you may be used to) Julia's loops are fast, and as a consequence you can always write such simple functions yourself. To see what I mean, take a look at the implementation of findnext
(in base/array.jl
); there's nothing "fancy" about it, yet you get performance that is just as good as what you'd get if you had implemented it in C.
Upvotes: 38