Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indices of unique elements of vector in Julia

Tags:

julia

How to get indexes of unique elements of a vector?

For instance if you have a vector v = [1,2,1,3,5,3], the unique elements are [1,2,3,5] (output of unique) and their indexes are ind = [1,2,4,5]. What function allows me to compute ind so that v[ind] = unique(v) ?

like image 397
Alex338207 Avatar asked Jun 17 '18 19:06

Alex338207


2 Answers

This is a solution for Julia 0.7:

findfirst.(isequal.(unique(x)), [x])

or similar working under Julia 0.6.3 and Julia 0.7:

findfirst.(map(a -> (y -> isequal(a, y)), unique(x)), [x])

and a shorter version (but it will not work under Julia 0.7):

findfirst.([x], unique(x))

It will probably not be the fastest.

If you need speed you can write something like (should work both under Julia 0.7 and 0.6.3):

function uniqueidx(x::AbstractArray{T}) where T
    uniqueset = Set{T}()
    ex = eachindex(x)
    idxs = Vector{eltype(ex)}()
    for i in ex
        xi = x[i]
        if !(xi in uniqueset)
            push!(idxs, i)
            push!(uniqueset, xi)
        end
    end
    idxs
end
like image 76
Bogumił Kamiński Avatar answered Sep 18 '22 13:09

Bogumił Kamiński


Another suggestion is

unique(i -> x[i], 1:length(x))

which is about as fast as the function in the accepted answer (in Julia 1.1), but a bit briefer.

like image 28
mattswoon Avatar answered Sep 20 '22 13:09

mattswoon