Julia: Find the indices of all maxima

12,498

Solution 1

If this is not a bottleneck

A = [1, 2, 3, 3, 3]
A_max = maximum(A)
find(a->a==A_max, A)

Will give you what you need, but it does go over the array twice.

Solution 2

You can also use comprehensions. The array will be iterated twice.

v = [1, 2, 3, 3, 3]
maxval = maximum(v)
positions = [i for (i, x) in enumerate(v) if x == maxval]

If performance is critical then the following algorithm may work:

function findallmax(arr)
    max_positions = Vector{Int}()
    min_val = typemin(eltype(arr))
    for i in eachindex(arr)
        if arr[i] > min_val
            min_val = arr[i]
            empty!(max_positions)
            push!(max_positions, i)
        elseif arr[i] == min_val
            push!(max_positions, i)
        end
    end
    max_positions
end

one iteration is required.

Share:
12,498

Related videos on Youtube

Code Pope
Author by

Code Pope

Software developer for more than a decade. "From my point of view, code is the light that illuminates the darkness, even if it does not dissolve it, and a spark of divine light is within each of us."

Updated on July 13, 2022

Comments

  • Code Pope
    Code Pope almost 2 years

    In Julia you can use findmax or indmax to find the index of the biggest entry in a matrix. But if you have multiple entries with this maximum value, you get the index of the first one. How can I get the indices of all max value entries in a matrix?

  • GNUSupporter 8964民主女神 地下教會
    GNUSupporter 8964民主女神 地下教會 almost 5 years
    find can no longer be found in the docs for v1.1.0.
  • passerby51
    passerby51 over 4 years
    As of now findall(A .== maximum(A)) seems to work.
  • passerby51
    passerby51 over 4 years
    or findall(x->x==maximum(A), A).
  • wueli
    wueli about 4 years
    The performance of findallmax depends heavily on the amount of new maxima found. I.e. findallmax(1:2000) takes 10 times longer than findallmax(2000:-1:1) and takes also longer than findall(A .== maximum(A)) in this case.