What is the simplest way to find the first index of some item in an array in Julia?
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Accessing element at a specific index in Julia – getindex() Method. The getindex() is an inbuilt function in julia which is used to construct array of the specified type. This function is also used to get the element of the array at a specific index.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
In Julia, to access the contents/particular element of an array, you need to write the name of the array with the element number in square bracket.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With