Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first index of an item in an array in Julia

Tags:

arrays

julia

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

like image 808
fhucho Avatar asked Nov 20 '13 17:11

fhucho


People also ask

How do you find the index of the first element of an array?

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.

How do you find the index of an element in Julia?

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.

How do you find the index of a number in an array?

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.

How do you access an element in an array Julia?

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.


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.

like image 184
tholy Avatar answered Oct 31 '22 10:10

tholy


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

like image 23
Mohammad Nazari Avatar answered Oct 31 '22 09:10

Mohammad Nazari