How to select elements from array in Julia matching predicate? How to select elements from array in Julia matching predicate? arrays arrays

How to select elements from array in Julia matching predicate?


You can use a very Matlab-like syntax if you use a dot . for elementwise comparison:

julia> a = 2:72:7julia> a .> 46-element BitArray{1}: false false false  true  true  truejulia> a[a .> 4]3-element Array{Int32,1}: 5 6 7

Alternatively, you can call filter if you want a more functional predicate approach:

julia> filter(x -> x > 4, a)3-element Array{Int32,1}: 5 6 7


Array comprehension in Julia is somewhat more primitive than list comprehension in Haskell or Python. There are two solutions — you can either use a higher-order filtering function, or use broadcasting operations.

Higher-order filtering

filter(x -> x > 4, a)

This calls the filter function with the predicate x -> x > 4 (see Anonymous functions in the Julia manual).

Broadcasting and indexing

a[Bool[a[i] > 4 for i = 1:length(a)]]

This performs a broadcasting comparision between the elements of a and 4, then uses the resulting array of booleans to index a. It can be written more compactly using a broadcasting operator:

a[a .> 4]


I'm currently using Julia 1.3.1 and some syntax has changed compared to earlier answers. To filter an array on multiple conditions I had to do:

x = range(0,1,length=100)x[(x .> 0.4) .& (x .< 0.51)] 

note the '.&' needed to do the AND operator.