Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Find the indices of all maxima

Tags:

max

indices

julia

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?

like image 238
Code Pope Avatar asked Jan 13 '17 14:01

Code Pope


2 Answers

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.

like image 70
pkofod Avatar answered Oct 21 '22 22:10

pkofod


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.

like image 37
novatena Avatar answered Oct 21 '22 20:10

novatena