Check all the values in a Julia array?

The functions any and count do this:

julia> a = [3,4,6,10,55,31,9,10]
8-element Array{Int64,1}:
  3
  4
  6
 10
 55
 31
  9
 10

julia> any(x->x==3, a)
true

julia> count(x->x==10, a)
2

However the performance will probably be about the same as a loop, since loops in julia are fast (and these functions are themselves implemented in julia in the standard library).

If the problem has more structure you can get big speedups. For example if the vector is sorted you can use searchsorted to find matching values with binary search.


You can also use broadcasted operations. In some cases it's nicer syntax than any and count, in other cases it can be less obvious what it's doing:

boola = a.>10 # Returns an Array{Bool}, true at any value >10
minimum(boola) # Returns false if any are <10
sum(a-10 .== 0) # Finds all values equal to 10, sums to get a count

Not sure if this had been implemented at the time of previous answers, but the most concise way now would be:

all(a .> 10)

As Chris Rackauckas mentioned, a .> 10 returns an array of booleans, and then all simply checks that all values are true. Equivalent of Python's any and all.

Tags:

Arrays

Julia