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.
Using findall() method The findall() method is used to find all the occurrences of the required element from an array, and return an Array (or CartesianArray, depending on the dimensions of input array) of the index, where the elements are present in the input array.
The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.
We can do this with the deleteat! function. (It looks like the function name is “delete eat” but it's actually “delete at” 😂). You can also delete a range of elements from an array using deleteat!()
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With