I am quite new in Julia and I don't know how to remove consecutive duplicates in an array. For example if you take this array :
`v=[8,8,8,9,5,5,8,8,1];`
I would like to obtain the vector v1 such that:
v1 = [8,9,5,8,1];
Could anyone help me? Many thanks.
One method could be to define:
function fastuniq(v)
v1 = Vector{eltype(v)}()
if length(v)>0
laste = v[1]
push!(v1,laste)
for e in v
if e != laste
laste = e
push!(v1,laste)
end
end
end
return v1
end
And with this function, you have:
julia> println(fastuniq(v))
[8,9,5,8,1]
But, when dealing with arrays, one need to decide if elements are to be deep or shallow copied. In case of integers, it doesn't matter.
In StatsBase.jl
there is an rle
function (Run-length encoding) that does exactly this.
This is a lot slower than @DanGetz's function but here is a way to do it in one line:
function notsofastunique(v)
return [v[1]; v[2:end][v[2:end] .!= v[1:end-1]]]
end
>println(notsofastunique(v))
[8,9,5,8,1]
Maybe it's useful for someone looking for a vecotrised solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With