How to select elements from array in Julia matching predicate?

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]

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

julia> a = 2:7
2:7

julia> a .> 4
6-element BitArray{1}:
 false
 false
 false
  true
  true
  true

julia> 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

Tags:

Arrays

Julia