Julia中向量唯一元素的索引 [英] indices of unique elements of vector in Julia

查看:26
本文介绍了Julia中向量唯一元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取向量中唯一元素的索引?

How to get indexes of unique elements of a vector?

例如,如果您有一个向量 v = [1,2,1,3,5,3],则唯一元素是 [1,2,3,5](unique 的输出)和它们的索引是 ind = [1,2,4,5].什么函数允许我计算 ind 以便 v[ind] = unique(v) ?

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) ?

推荐答案

这是 Julia 0.7 的解决方案:

This is a solution for Julia 0.7:

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

在 Julia 0.6.3 和 Julia 0.7 下或类似的工作:

or similar working under Julia 0.6.3 and Julia 0.7:

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

还有一个更短的版本(但在 Julia 0.7 下无法使用):

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

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

它可能不会是最快的.

如果您需要速度,您可以编写类似的东西(应该在 Julia 0.7 和 0.6.3 下都可以使用):

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

这篇关于Julia中向量唯一元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆