ismember

Tests whether elements of one set belong to another set.

Category: Language Fundamentals > Data Types

Syntax

tf = ismember(A, S)

Returns true for each element of A that is found in S.

[tf, loc] = ismember(A, S)

Also returns the index in S of each match.

Description

ismember is the usual tool for filtering by membership, for example keeping only the rows whose code appears in an allowed list. Cell arrays of text are compared as whole strings. NaN never matches NaN, because the two are not equal.

The second output turns the function into a lookup: loc can be used to index into data that is parallel to S.

Input arguments

A
Elements to look up: numbers, characters, strings, or a cell array of character vectors. A single text value is treated as one element.
S
The set to search in, of a compatible type.

Output arguments

tf
Logical array the same size as A.
loc
Double array the same size as A: the index in S of the matching element, or 0 when there is none.

Example

Membership and positions

[tf, loc] = ismember([1 5 2 2], [2 1 0])
ismember({'a','q'}, {'a','b'})
ismember(NaN, [NaN 1])
Output
tf = 1×4 logical array

   1   0   1   1
loc = 1×4

     2     0     1     1
ans = 1×2 logical array

   1   0
ans = logical
   0

See also

unique intersect setdiff union find contains