25

What is the simplest way to find the first index of some item in an array in Julia?

2 Answers 2

38

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.

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

3 Comments

Can you add links to documentation for findfirst() and findnext()?
docs.julialang.org/en/latest/base/arrays/#Base.findfirst-Tuple{Any} and then just keep reading (findnext comes a little later in the same page).
8

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

According to the document, you can use ‍‍isequal(2) instead of myCondition, but I get the error: no method matching isequal(::Int64).
Is there a way the function will support getting additional value instead of the constant 2?

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.