Filtering using conditional evaluation (&&)

Viewed 44

I am having trouble filtering a simple array-based on two conditions. For example, to filter out values between 3 and 5, I tried the following but I get an ERROR: TypeError: non-boolean (BitArray{1}) used in boolean context error.

 arr = Array{Int64}([1,2,3,4,5,6])
 arr[(arr .> 3) && (arr.< 5)]

Any idea how to solve it?

Also on a side note, I am wondering if there is a function opposite to isless. Something to find a value greater than a certain value.

3 Answers

Here are two ways to do it:

julia> arr = [1,2,3,4,5,6]
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> arr[(arr .> 3) .& (arr.< 5)]
1-element Array{Int64,1}:
 4

julia> filter(v -> 3 < v < 5, arr)
1-element Array{Int64,1}:
 4

(I personally prefer filter).

To get the opposite of isless just reverse its arguments, or if needed define a new function:

isgreater(x, y) = isless(y, x)

I prefer a set comparison approach because it's quite intuitive:

julia> arr = Array{Int64}([1,2,3,4,5,6])

julia> intersect( arr[ arr .> 1 ], arr[ arr .< 4 ] )
2-element Array{Int64,1}:
 2
 3

Or list comprehension:

    [ x for x in arr if 3 < x < 5]
    # or
    [ x for x in arr if 3 < x && x < 5]

Also to define an array literal with specific type Int64, there is a dedicated syntax to make it simpler:

    arr = Int64[1,2,3,4,5,6]
Related