Julia中如何实现类似Matlab ismember的字符串数组匹配逻辑向量
ismember in Julia To replicate MATLAB's ismember(A, B) functionality—getting a boolean vector indicating which elements of array A are present in array B—you'll want to use Julia's in operator with broadcasting, paired with a Set for efficient membership checks. Here's how to do it with your example:
# Define your input arrays A = ["me", "you", "us"] B = ["me", "us"] # Convert B to a Set for fast O(1) membership checks (critical for large arrays) B_set = Set(B) # Option 1: Using a comprehension (readable and straightforward) myLogicalVector = [x in B_set for x in A] # Option 2: Using dot syntax with Ref (concise, idiomatic Julia) myLogicalVector = in.(A, Ref(B_set))
Both approaches will return Bool[true, false, true], exactly matching your MATLAB output.
Why occursin didn't work
You're correct about the limitation of occursin: this function checks if one string is a substring of another, not if an element is part of a collection. So:
occursin.(A, B)works only ifAandBare the same length (checking each element ofAis a substring of the corresponding element ofB), or if one is a scalar (checking that scalar is a substring of every element in the other array). This isn't what you need for set membership.
Efficiency note
Using Set(B) instead of the original array B is important for performance, especially when B is large. Checking membership in a Set is constant time, whereas checking against an array is linear time (scaling with the size of B). For small arrays, either approach will work, but Set is the better practice for larger datasets.
内容的提问来源于stack exchange,提问作者ForzaRS

