Skip to main content
v2026.11,986 entries · CC-BY 4.0

ismember MATLAB: Syntax, Rows and Tolerance

Learn how to use ismember in MATLAB to find set members in arrays, match matrix rows, filter research tables, and resolve floating-point precision issues.

Written and maintained by CASRAI Editorial Board

Published

On this page

In MATLAB, the ismember function tests set membership across arrays, matrices, cell arrays, and data tables. It identifies whether elements in a test dataset exist within a reference set, returning a logical array indicating membership and an optional index array identifying the location of each match. In research data analysis, mastering ismember and matlab ismember operations is essential for cohort segmentation, multi-condition experimental filtering, coordinate verification, and relational data matching across large scientific datasets.

What it is used for in research

Scientific computing workflows routinely process complex observational, experimental, and simulated datasets that require matching observations against reference lists or inclusion criteria. In scientific computing in MATLAB, the ismember function serves several primary research functions:

  • Experimental Cohort Filtering: Isolating participant identifiers, animal tag numbers, or clinical sample IDs that match specific inclusion or exclusion criteria across multi-center trials.
  • Tabular Data Subsetting: Selecting rows from a MATLAB data table where categorical groupings, subject markers, or timestamp records match predefined target lists.
  • Spatial Coordinate and Grid Verification: Testing whether 2D or 3D coordinate pairs (such as sensor locations or pixel coordinates) exist within a calibration grid using the row-comparison syntax.
  • Genomic and Multi-Omics Feature Matching: Screening high-throughput probe IDs, gene symbols, or metabolite accession strings stored in a MATLAB cell array or string array against reference biological pathways.
  • Trial State and Event Tracking: Identifying discrete simulation events or hardware state transitions that belong to predefined behavioral phases.

Install or access (official source only)

The ismember function is a built-in core function of standard MATLAB and GNU Octave. It does not require any add-on toolboxes, specialized licenses, or external package installations.

  • MATLAB Desktop: Accessible via local installation on Windows, macOS, or Linux, acquired through the official MathWorks portal (mathworks.com/downloads) under standard academic campus-wide, institutional, or individual licenses.
  • MATLAB Online: Accessible through any modern web browser at matlab.mathworks.com using authenticated MathWorks institutional or student account credentials.
  • Command-Line Documentation: To inspect the integrated reference documentation and function signatures directly in the MATLAB Command Window, enter:
    help ismember
    doc ismember
  • Environment Verification: Running which ismember confirms that the function resolves to the built-in elementary math and data structures library of your active MATLAB runtime.

Step-by-step task

Follow these numbered steps to execute set membership checks, index lookups, row comparisons, and table filtering in MATLAB:

Step 1: Test 1D Vector Membership

To check which elements of vector A exist anywhere in vector B, call ismember(A, B). The function returns a logical vector lia possessing the exact dimensions of A:

% Define sample experimental measurements and target threshold values
A = [12, 24, 35, 48, 60, 72];
B = [24, 60, 95];

% Test membership
lia = ismember(A, B);
% lia returns: [0, 1, 0, 0, 1, 0]

Step 2: Retrieve Matching Index Positions

Requesting two output arguments returns both the logical indicator and an array locb containing the first matching index position in B for each corresponding element in A (or 0 if no match exists):

[lia, locb] = ismember(A, B);
% lia  returns: [0, 1, 0, 0, 1, 0]
% locb returns: [0, 1, 0, 0, 2, 0]

Here, 24 is located at index 1 of B, and 60 is located at index 2 of B. Elements without matches return 0.

Step 3: Compare Rows in Multi-Column Matrices

When working with spatial coordinates, feature vectors, or multi-channel measurements, use the 'rows' flag. Both matrices must have an identical number of columns:

% Sample coordinate pairs [X, Y]
sampleCoords = [1.0, 2.0; 3.0, 4.0; 5.0, 6.0; 7.0, 8.0];
calibrationGrid = [0.0, 0.0; 3.0, 4.0; 7.0, 8.0];

% Match entire rows
[liaRows, locbRows] = ismember(sampleCoords, calibrationGrid, 'rows');
% liaRows  returns: [0; 1; 0; 1]
% locbRows returns: [0; 2; 0; 3]

Step 4: Filter Research Data Tables Using Logical Indexing

In structured scientific analysis, use ismember to construct a logical mask for MATLAB indexing across tabular datasets:

% Create an experimental cohort table
SubjectID = [101; 102; 103; 104; 105];
Score = [78.2; 88.5; 64.1; 92.0; 81.4];
Cohort = categorical({'Control'; 'Active'; 'Active'; 'Control'; 'Active'});
trialData = table(SubjectID, Score, Cohort);

% Define target subjects to extract
selectedSubjects = [102; 105];

% Extract subset using logical masking
mask = ismember(trialData.SubjectID, selectedSubjects);
activeCohort = trialData(mask, :);

Step 5: Test Membership Across Cell Arrays and String Arrays

For qualitative descriptors, sample annotations, or biological identifiers, ismember operates natively on string arrays and cell arrays of character vectors:

geneList = ["BRCA1", "TP53", "EGFR", "MYC", "PTEN"];
targetPanel = ["TP53", "PTEN", "KRAS"];

geneMask = ismember(geneList, targetPanel);
% geneMask returns: [0, 1, 0, 0, 1]

Output and how to read it

Understanding the structure and data types returned by ismember prevents indexing errors and unexpected logical operations:

  • First Output (Lia): A logical array matching the exact dimensions and size of the input array A. Each element contains true (logical 1) if that specific element of A is present anywhere within B, and false (logical 0) otherwise. When using 'rows' on an m × n matrix, Lia is an m × 1 logical column vector.
  • Second Output (Locb): An array of type double matching the size of A. If an element in A matches one or more elements in B, Locb contains the lowest linear index in B where that value occurs. If an element has no match in B, Locb evaluates to 0.
  • Zero-Index Precaution: MATLAB uses 1-based indexing. Because unmatched elements evaluate to 0 in Locb, attempting to index directly into B(locb) will trigger an out-of-bounds error (Subscript indices must either be real positive integers or logicals). Always gate indexing with lia:
    matchedB = B(locb(lia));
  • Algorithmic Complexity: ismember sorts the reference set and performs binary search lookups, providing O(n log2(m)) scaling efficiency rather than the O(n × m) penalty incurred by brute-force nested comparison loops.

Troubleshooting

Address common operational issues and edge cases when working with ismember in MATLAB:

1. Floating-Point Rounding Failures (The Precision Trap)

Because ismember demands exact binary bit-level equality, floating-point calculations frequently fail to match due to IEEE 754 precision artifacts. For example, ismember(0.1 + 0.2, 0.3) evaluates to false.

Fix: Use the dedicated tolerance-aware companion function ismembertol for floating-point data:

A_float = [0.1 + 0.2, 1.0000001];
B_float = [0.3, 1.0];

% Fails with exact ismember
exactMatch = ismember(A_float, B_float); % returns [0, 0]

% Succeeds with ismembertol using relative tolerance
tolMatch = ismembertol(A_float, B_float, 1e-5); % returns [1, 1]

2. Matrix Dimension Mismatch Under ‘rows’

If you execute ismember(A, B, 'rows') when matrix A and matrix B have different numbers of columns, MATLAB throws an error: Inputs must have the same number of columns to use the 'rows' flag.

Fix: Inspect column counts with size(A, 2) and size(B, 2). Ensure both matrices represent identical variable dimensions before comparing row entries.

3. Character Vectors vs String Arrays

Passing a single character vector such as 'Control' treats the input as a 1 × 7 character array, testing each individual character against B rather than evaluating the entire word.

Fix: Enclose text elements in double quotes (string array: "Control") or curly braces (cell array of character vectors: {'Control'}) to treat text labels as distinct individual tokens.

4. Working with NaN Values

By standard IEEE 754 definitions, NaN == NaN evaluates to false. In ismember, however, NaN values are considered equal to each other when comparing numeric arrays. If A contains NaN and B contains NaN, ismember(NaN, [1, NaN, 3]) returns true. If you need to disregard missing values, filter them beforehand using isnan.

Free alternatives (table)

While MATLAB provides a polished environment for matrix operations, several open-source programming languages offer equivalent set membership capabilities for reproducible research. The following table compares primary tools:

Software / Package Primary Function Row-Wise Matching Index Retrieval Tolerance Comparison License Model
MATLAB ismember(A, B) Yes ('rows' flag) Yes ([lia, locb]) Yes (via ismembertol) Commercial proprietary
GNU Octave ismember(a, s) Yes ('rows' flag) Yes ([tf, s_idx]) Yes (via ismembertol) Free open-source (GPLv3)
Python (NumPy) numpy.isin(a, b) Requires structured view Requires np.nonzero() Requires np.isclose() Free open-source (BSD)
R (base) x %in% table Requires merge / semi_join Yes (via match(x, table)) Custom distance threshold Free open-source (GPLv2/v3)
Julia (Base) in.(A, Ref(B)) Yes (via eachrow) Yes (via findfirst) Yes (via isapprox) Free open-source (MIT)

For researchers migrating or establishing open-science pipelines without commercial dependencies, GNU Octave provides direct drop-in script compatibility with MATLAB ismember and ismembertol syntax. For multi-language workflows evaluating Python, R, and Julia ecosystems, consult our detailed analysis in MATLAB vs R for research.

FAQ

What does ismember do in MATLAB?

The ismember function checks whether elements of a test array exist in a reference set. It outputs a logical array indicating which elements are present, and can optionally output an index vector showing the first matching position in the reference set.

How do I return the index location of matching elements?

Call ismember with two output arguments: [lia, locb] = ismember(A, B). The second variable, locb, contains the 1-based index of the first occurrence in B for each element in A that matched. Elements in A that do not appear in B receive a value of 0.

Why does ismember fail on decimal values?

Standard ismember performs exact bitwise comparison. Due to floating-point rounding errors inherent to binary arithmetic, computed numbers rarely equal identical decimal representations. Use ismembertol(A, B, tol) to evaluate floating-point membership within a defined numerical tolerance.

How do I match entire rows between two matrices?

Pass the 'rows' argument: lia = ismember(A, B, 'rows'). Both matrices must share the same number of columns. MATLAB evaluates each row as a single unit and returns a logical column vector indicating which rows of A are present in B.

Can ismember filter rows in a MATLAB data table?

Yes. You can test membership on a specific table column, such as mask = ismember(dataTable.SubjectID, targetIDs), and then use that logical vector to slice the table: filteredTable = dataTable(mask, :).

What is the difference between ismember and intersect?

The ismember function evaluates set membership while preserving the exact size, shape, and element order of the input array A. In contrast, intersect extracts only the common values between two sets, returning a sorted, deduplicated vector of unique shared elements.

Sources (official docs)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about ismember MATLAB: Syntax, Rows and Tolerance

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →