Julia中向量的唯一元素的索引 [英] indices of unique elements of vector in 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屋!