Subset of a vector

Viewed 67

I would like to subset a vector by a simple condition and keep result in the initial vector:

x = [1,2,3,4,5]
y = 4
x = x[x .< 4]

1 2 3

It works fine but if I have longer variable name, it looks like this:

position = position[position .< 4]

Is there other more elegant way to do this without typing the same variable name 3 times in Julia.

1 Answers
julia> x = [1,2,3,4,5];

julia> filter!(<(4), x)
3-element Vector{Int64}:
 1
 2
 3

This makes an in-place filtering, if you want rather a copy use filter(<(4), x) instead.

Note that the filter! function is the fastest possible way to filter a vector in such scenario.

julia> x = [1,2,3,4,5]

julia> @btime filter!(<(4), $x)
  5.500 ns (0 allocations: 0 bytes)

julia> x = [1,2,3,4,5]

julia> @btime $x = $x[$x .< 4];
  94.618 ns (3 allocations: 176 bytes)
Related