Julia: How to find the locations of strings (in a string array) in another string array

Viewed 490

I want to return a logical vector showing the location of strings that are members of two string arrays A and B.

In Matlab, this would be

A = ["me","you","us"]
B = ["me","us"]
myLogicalVector = ismember(A,B)

myLogicalVector =

  1×3 logical array

   1   0   1

How do I achieve this in Julia?

I have tried

myLogicalVector = occursin.(A,B)
myLogicalVector = occursin(A,B)

It seems that occursin only works if the two input string arrays are of the same length or one string is a scalar - I am not sure if I am correct on this one.

1 Answers

You can write:

julia> in(B).(A)
3-element BitArray{1}:
 1
 0
 1

more verbose versions of similar operation are (note that the type of array is different in all cases except the first):

julia> in.(A, Ref(B))
3-element BitArray{1}:
 1
 0
 1

julia> [in(a, B) for a in A]
3-element Array{Bool,1}:
 1
 0
 1

julia> map(a -> in(a, B), A)
3-element Array{Bool,1}:
 1
 0
 1

julia> map(a -> a in B, A)
3-element Array{Bool,1}:
 1
 0
 1

julia> [a in B for a in A]
3-element Array{Bool,1}:
 1
 0
 1

If A and B were large and you needed performance then convert B to a Set like this:

in(Set(B)).(A)

(you pay one time cost of creation of the set, bu then the lookup will be faster)

Related