logo

Julia's find functions 📂Julia

Julia's find functions

Overview

Julia’s basic built-in functions are increasingly useful the more you know them. Without further ado, let’s learn through examples.

Code

x = [3, 7, 4, 5, 10, 3, 12, 3, 2, 4]

argmin(x)
argmax(x)
findmin(x)
findmax(x)
extrema(x)

findfirst(x .== 3)
findlast(x .== 3)
findall(x .== 3)

findnext(x .== 3, 5)
findprev(x .== 3, 5)

Optimal solutions argmin(),argmax(),findmin(),findmax(),extrema()

Finding the optimal solutions.

x = [3, 7, 4, 5, 10, 3, 12, 3, 2, 4]

julia> argmin(x)
9

julia> argmax(x)
7

y = [7, 8, 9, 9, 7, 9]

julia> argmax(y)
3

julia> findall(y.==maximum(y))
3-element Vector{Int64}:
 3
 4
 6

argmin(),argmax() simply return the index of the optimal solution, i.e., the index where the value is the largest or smallest. If there are multiple indices, it returns the smallest one. So, in fact, argmax(x) $= \min(\argmax(x))$. The real $\argmax$ is done using maximum() along with the findall() function.

x = [3, 7, 4, 5, 10, 3, 12, 3, 2, 4]

julia> findmin(x)
(2, 9)

julia> findmax(x)
(12, 7)

findmin(),findmax() return the optimal solution along with its value.

x = [3, 7, 4, 5, 10, 3, 12, 3, 2, 4]

julia> extrema(x)
(2, 12)

Note that extrema() returns not the indices but only the values. This is similar to the range() function in R1.

First/Last index meeting a condition findfirst(), findlast()

x = [3, 7, 4, 5, 10, 3, 12, 3, 2, 4]

julia> findfirst(x .== 3)
1

julia> findlast(x .== 3)
8

Found the first and last index where 3 is located. If the shape of the array can be roughly anticipated, these can be used to improve the speed of the code.

All indices that meet a condition findall()

x = [3, 7, 4, 5, 10, 3, 12, 3, 2, 4]

julia> findall(x .== 3)
3-element Vector{Int64}:
 1
 6
 8

This is the most convenient to use and the most useful function in general programming. Used with maximum(), minimum(), it finds all $\text{argmin}

Specific range of indices meeting a condition findnext(), findprev()

julia> findnext(x .== 3, 5)
6

julia> findprev(x .== 3, 5)
1

Sometimes, we may need to search beyond exceptions. For instance, using findall() to find an element identical to the first element of an array would also find that first element itself, which could be cumbersome.

Environment

  • OS: Windows
  • julia: v1.7.0