Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcast version of in() function or in operator?

Tags:

julia

Consider an array, say 0 to 4. I want to test if each element is in a list and return an array of booleans. A call to in returns a single boolean, because this left-hand side array is not an element of the right-hand side array:

> a = 0:4;
> a in [1, 2]
false

Does Julia have a broadcast version of the in() function or the in operator that returns an array like this call to map and a lambda function?

> map(x -> x in [1,2], a)
5-element Array{Bool,1}:
 false
  true
  true
 false
 false
like image 717
miguelmorin Avatar asked Sep 02 '25 09:09

miguelmorin


1 Answers

You can use broadcasting, but you have to tell Julia that the second argument should not be iterated over, so you should do:

julia> in.(a, [[1,2]])
5-element BitArray{1}:
 false
  true
  true
 false
 false

or

julia> in.(a, Ref{Vector{Int}}([1,2]))
5-element BitArray{1}:
 false
  true
  true
 false
 false

Both will work under Julia 0.6.3 and 0.7.

Similarly, the operator (\inTAB, synonymous with the in function) allows for broadcasting using infix notation.

julia> 0:4 .∈ [[1,2]]
5-element BitArray{1}:
 false
  true
  true
 false
 false
like image 193
Bogumił Kamiński Avatar answered Sep 04 '25 23:09

Bogumił Kamiński