Reputation: 4352
Given a 1D array in Julia, find all elements which are between a (= 4) and b( = 7), in place.
a = 4;b = 7;
x = collect(1:10)
x[isless.(x,a)]
will find all the elements in array which are less than a = 4.
How to combine two logical operations in indexing.
x[isless.(x,a) && !isless.(x,b)]
is not working out.
Upvotes: 1
Views: 296
Reputation: 69839
If you are OK with <
operator instead of isless
(which is most likely the case unless you work with NaN
, missing
, or -0.0
) then you can write:
julia> x[a .< x .< b]
2-element Vector{Int64}:
5
6
Alternatively you can use filter
:
julia> filter(v -> a < v < b, x)
2-element Vector{Int64}:
5
6
which brings me to the reason why I added this comment. You asked for an in place operation. This is not possible with indexing, but you can achieve it with filter!
if you work with Vector
:
julia> filter!(v -> a < v < b, x)
2-element Vector{Int64}:
5
6
julia> x
2-element Vector{Int64}:
5
6
Upvotes: 5
Reputation: 2554
You'll need to use broadcast &&
(or, on older Julia versions, &
):
julia> x[isless.(x,b) .&& (!isless).(x,a)]
3-element Vector{Int64}:
4
5
6
julia> x[isless.(x,a) .& (!isless).(x,b)]
Int64[]
The other thing to be careful about is the precedence of !
vs .
-- you'll either need to use (!isless).(x, a)
or .!isless.(x, a)
to get the right broadcasting behaviour.
Upvotes: 4