You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Julia中如何实现类似Matlab ismember的字符串数组匹配逻辑向量

Equivalent of MATLAB's 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 if A and B are the same length (checking each element of A is a substring of the corresponding element of B), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:17:19