What is the simplest way to find the first index of some item in an array in Julia?
2 Answers
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.
3 Comments
findnext comes a little later in the same page).findfirst: https://docs.julialang.org/en/v1/base/arrays/#Base.findfirst-Tuple{Any}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
2 Comments
isequal(2) instead of myCondition, but I get the error: no method matching isequal(::Int64).