Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check all the values in a Julia array?

Tags:

arrays

julia

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.

like image 556
Unknown Coder Avatar asked Aug 29 '16 23:08

Unknown Coder


People also ask

How do you find the element of an array in Julia?

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.

How do you determine the size of a Julia Matrix?

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.

How do you remove an element from an array in Julia?

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!()


3 Answers

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.

like image 82
Jeff Bezanson Avatar answered Oct 17 '22 09:10

Jeff Bezanson


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.

like image 44
gsarret Avatar answered Oct 17 '22 08:10

gsarret


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
like image 31
Chris Rackauckas Avatar answered Oct 17 '22 08:10

Chris Rackauckas