Check all the values in a Julia array?
Solution 1
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.
Solution 2
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
.
Solution 3
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
Unknown Coder
Updated on June 16, 2022Comments
-
Unknown Coder almost 2 years
How can I check all the values in a Julia array at once? Let's say I have an array like
a=[3,4,6,10,55,31,9,10]
How can I check if the array has any values greater than 10? Or how can I check if there are repeating values (like the 10 that is contained twice in the sample? I know I can write loops to check this, but I assume Julia has a faster way to check all the values at once.