2

I want to check elementwise (or broadcast) if the elements of vector x are in the vector y in Julia like what the function checkin does:

x = ["one", "two", "three", "four"]
y = ["two", "three", "five", "four"]

function checkin(x,y)
    for i = 1:length(y)
        if y[i] ∈ x
            println(true)
        else 
            println(false)
        end
    end
end
checkin(x,y)

output:

true
true
false
true

If I type

x .∈ y

or

x .in y

I get an error

As often, I'm sure that there exist a much easier way to do it as writting a 9 line function, but I couldn't find it

ecjb
  • 5,169
  • 12
  • 43
  • 79

1 Answers1

6

Use:

in.(y, Ref(x))

You have to wrap x in Ref or write (x, ) or [x] in order make broadcast always take x and not iterate over it.

Note that I have written it so that you check if y[i] is in x for i in eachindex(y) because this was the way your reference implementation was done.

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • Many thanks once more @Bogumił Kamiński. Is `Ref` the same as in https://github.com/JuliaLang/julia/blob/master/base/refpointer.jl ? – ecjb Feb 10 '19 at 13:23
  • 1
    Yes, but in this application just think of it as 0-dimensional container holding `x` that has exactly one element. It is better to use `Ref` than e.g. `[x]` because it is immutable and in hot code will not cause Julia to make additional allocations. `(x,)` should be equally fast to `Ref(x)`. – Bogumił Kamiński Feb 10 '19 at 13:27