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

MATLAB strcmp: Text Comparison Syntax & Rules

Compare text in MATLAB using strcmp. Learn exact syntax, character vector vs string array rules, dimension safety, Octave alternatives, and error fixes.

Written and maintained by CASRAI Editorial Board

Published

On this page

The strcmp function in MATLAB tests whether two text inputs are identical in content and dimensions, returning a logical 1 (true) when they match and 0 (false) when they differ. When writing automated analysis pipelines in MATLAB coding workflows, scientific researchers frequently compare experimental group labels, categorical metadata, gene identifiers, and trial codes. Understanding how strcmp behaves across legacy character vectors, modern string arrays, and cell arrays is critical for preventing runtime dimension mismatch errors and writing robust analytical software.

What it is used for in research

In quantitative and computational research, datasets routinely contain text labels that classify experimental conditions, demographic categories, or biological specimens. The primary role of strcmp matlab implementations in scientific scripts is to perform safe, case-sensitive string matching without the structural fragility associated with standard relational equality operators.

In MATLAB, applying the standard relational operator == to traditional character vectors (strings enclosed in single quotation marks, such as 'Control') performs an element-by-element character comparison. If the two character vectors have different lengths—such as comparing 'Control' (7 characters) with 'Treated' (7 characters) versus 'Placebo' (7 characters) and 'Vehicle' (7 characters) or 'WildType' (8 characters)—MATLAB throws a fatal matrix dimension agreement error: Matrix dimensions must agree. By contrast, strcmp accommodates character vectors of arbitrary and differing lengths safely, returning logical 0 without halting pipeline execution.

Researchers routinely use strcmp to:

  • Filter tabular experimental observation tables by matching specimen labels against control or cohort group names.
  • Validate parameter keys and configuration flags passed into custom laboratory analysis functions.
  • Control conditional execution pathways in automated scripts using MATLAB if conditional branches.
  • Index and subset high-dimensional cell arrays containing clinical trial participant identifiers or environmental sensor tags.

Install or access

The strcmp function is a core, built-in mathematical and string manipulation primitive included with all base installations of MathWorks MATLAB. It requires no additional toolboxes, domain modules, or specialized add-on licenses.

Researchers can access MATLAB and the strcmp function through the following standard distribution environments:

  • Desktop Installation: Installed locally on Linux, macOS, or Microsoft Windows via the MathWorks installer and activated through an institutional, laboratory, or personal MathWorks license.
  • MATLAB Online: Accessed directly through any modern web browser at matlab.mathworks.com using standard MathWorks institutional single sign-on credentials.
  • MATLAB Batch / Headless Compute: Executed in high-performance computing (HPC) clusters via terminal commands such as matlab -batch "run_analysis" or matlab -nodisplay -nosplash.

To verify that MATLAB is installed and check the active environment version, type the following command into the MATLAB Command Window:

version

Step-by-step task

Follow these numbered steps to compare text inputs, search cell arrays, and filter scientific dataset records using strcmp.

1. Compare Two Character Vectors

To evaluate whether two character vectors are identical, pass both vectors as arguments into strcmp:

sample_a = 'WildType';
sample_b = 'WildType';
sample_c = 'KnockOut';

match_ab = strcmp(sample_a, sample_b); % returns logical 1 (true)
match_ac = strcmp(sample_a, sample_c); % returns logical 0 (false)

2. Evaluate Case Sensitivity

Because strcmp is strictly case-sensitive, variations in letter casing evaluate to false. When case-insensitive comparison is required, use strcmpi:

str1 = 'Assay_Batch_A';
str2 = 'assay_batch_a';

exact_match = strcmp(str1, str2);   % returns logical 0
ignore_case = strcmpi(str1, str2);  % returns logical 1

3. Search and Index Within a Cell Array

Experimental datasets frequently store sample metadata as cell arrays of character vectors. When comparing a single reference string against a cell array, strcmp performs element-wise comparisons and returns a logical array matching the dimensions of the cell array:

cohorts = {'Control', 'Treatment_A', 'Control', 'Treatment_B', 'Treatment_A'};
is_control = strcmp('Control', cohorts);
% is_control evaluates to: [1 0 1 0 0]

% Extract indices of all control samples:
control_indices = find(is_control);
% control_indices evaluates to: [1, 3]

4. Filter Rows in Tabular Data Structures

Researchers working with experimental data tables can use the logical vector produced by strcmp to subset table rows directly:

% Construct an illustrative experimental table
SubjectID = {'S01'; 'S02'; 'S03'; 'S04'};
Group = {'Control'; 'Treatment'; 'Control'; 'Treatment'};
Measurement = [12.4; 18.2; 11.9; 19.5];
dataTable = table(SubjectID, Group, Measurement);

% Filter table for Control group records
controlRows = strcmp(dataTable.Group, 'Control');
controlData = dataTable(controlRows, :);

5. Implement Safe Conditional Branching

Integrate strcmp into control structures such as an if-else in MATLAB construct or a MATLAB switch statement to direct analytical workflows safely:

normalisation_method = 'zscore';

if strcmp(normalisation_method, 'zscore')
    disp('Applying standard score normalization...');
elseif strcmp(normalisation_method, 'minmax')
    disp('Scaling variables across unit range...');
else
    error('Unrecognized normalisation method specified.');
end

Output and how to read it

The output of strcmp is always of data type logical. Understanding the dimensions and format of the output depends on whether the inputs are scalar text items or text arrays.

Return Values and Dimension Rules

  • Two scalar inputs: Returns a single logical scalar: 1 (true) if both inputs match exactly across all characters, lengths, and casing; otherwise 0 (false).
  • Array and scalar text input: When one input is a cell array of character vectors or a string array and the second input is a single character vector or string scalar, strcmp returns a logical array of the exact same dimensions as the array input. Each element in the logical array indicates whether the corresponding element matches the scalar text.
  • Two arrays of identical size: When both inputs are cell arrays or string arrays of identical dimensions, strcmp evaluates corresponding elements pairwise and returns a logical array of that size.

Comparison with C Language strcmp

A frequent trap for researchers transitioning from C or C++ is that MATLAB reverses the logical convention of strcmp:

  • In C standard library: strcmp(s1, s2) returns 0 when strings are identical (representing zero difference), and a non-zero integer when they differ.
  • In MATLAB: strcmp(s1, s2) returns 1 (true) when strings are identical, and 0 (false) when they differ.

Text Comparison Methods in MATLAB

The table below summarizes the operational differences between string comparison functions and relational operators in MATLAB:

Comparison Method Target Data Types Case Sensitive Behavior on Unequal Char Lengths Primary Intended Use
strcmp(s1, s2) Char vectors, string arrays, cell arrays Yes Returns 0 safely without errors Exact string equality check across any text format
strcmpi(s1, s2) Char vectors, string arrays, cell arrays No Returns 0 safely without errors Case-insensitive text matching (e.g. user input)
strncmp(s1, s2, n) Char vectors, string arrays, cell arrays Yes Compares first n characters safely Prefix and header identification
strncmpi(s1, s2, n) Char vectors, string arrays, cell arrays No Compares first n characters safely Case-insensitive prefix matching
s1 == s2 (with strings "") Modern string arrays Yes Broadcasts or element-wise comparison Element-wise vector comparison in modern string data
s1 == s2 (with chars '') Character vectors Yes Throws matrix dimension agreement error Character-by-character ASCII comparison (avoid for equality)
isequal(s1, s2) Any data types Yes Returns 0 safely if sizes/types differ Strict structural and content identity across arbitrary objects

Troubleshooting

When executing string comparisons in research code, common discrepancies arise from whitespace, data typing, or missing values.

1. Unexpected Inequality Due to Trailing Whitespace

In MATLAB character vectors, trailing spaces are treated as significant characters. For example, strcmp('SampleA ', 'SampleA') evaluates to false. To eliminate spurious mismatches caused by inconsistent text padding during file importation, strip surrounding whitespace with strtrim:

clean_str1 = strtrim(raw_str1);
clean_str2 = strtrim(raw_str2);
is_match = strcmp(clean_str1, clean_str2);

2. Dimension Mismatch Error Using == on Character Vectors

If your script fails with Error using ==: Matrix dimensions must agree or Dimensions of matrices being concatenated are not consistent, the code is using the relational equality operator == on character vectors of unequal lengths (e.g., 'male' == 'female'). Replace the relational operator with strcmp:

% Flawed legacy code:
% if gender == 'female' % Crashes if gender is 'male'

% Correct implementation:
if strcmp(gender, 'female')
    % Safe execution regardless of character length
end

3. Comparing String Arrays Containing Missing Elements

Modern MATLAB string arrays can contain missing values represented as <missing>. When comparing strings with strcmp, comparing any string against <missing> evaluates to false. To explicitly identify missing elements in a dataset, use the ismissing function:

str_array = ["Batch_1", missing, "Batch_2"];
is_b1 = strcmp(str_array, "Batch_1");      % [1, 0, 0]
has_missing = ismissing(str_array);       % [0, 1, 0]

4. Cell Arrays with Mixed Data Types

If a cell array contains non-text elements (such as numeric values or empty matrices alongside character vectors), passing it to strcmp will evaluate the non-text elements as false rather than throwing an error. However, if strict data type consistency is expected, convert heterogeneous cell arrays to string arrays using string() prior to batch comparison.

Free alternatives

For scientific research environments seeking open-source computational platforms to ensure software reproducibility without proprietary licensing, several mature alternatives provide equivalent string comparison functionality:

Platform / Language Equivalent Syntax License Compatibility & Research Considerations
GNU Octave strcmp(s1, s2) GPLv3 Direct drop-in syntax compatibility with MATLAB. Returns 1 for match and 0 for non-match, supporting cell arrays of strings.
Python (NumPy) numpy.char.equal(a, b) BSD-3-Clause Vectorized element-wise string comparison across NumPy string and unicode arrays, returning boolean mask arrays.
Python (Pandas) df['col'] == 'target' BSD-3-Clause Standard relational equality for tabular data series, returning a boolean series for dataset filtering.
Julia s1 == s2 MIT Base language operator provides high-performance scalar and vectorized string equality checks (s1 .== s2).
R s1 == s2 or identical(s1, s2) GPL-2 / GPL-3 Vectorized character vector comparison in base R; identical() evaluates strict object equivalence.

FAQ

What is the difference between strcmp and strcmpi in MATLAB?

strcmp is strictly case-sensitive, meaning strcmp('Data', 'data') evaluates to logical 0 (false). In contrast, strcmpi performs case-insensitive comparisons, so strcmpi('Data', 'data') evaluates to logical 1 (true). Use strcmpi when matching user input or identifiers where character casing is non-standardized.

How does MATLAB strcmp differ from the C language strcmp?

In standard C, strcmp returns 0 when strings are identical, and a positive or negative integer when they differ. In MATLAB, strcmp adheres to standard boolean logic: it returns 1 (true) when text inputs are identical and 0 (false) when they differ.

Should I use strcmp or == to compare text in MATLAB?

For legacy character vectors enclosed in single quotes ('text'), always use strcmp; using == performs element-by-element character checks and throws a fatal error if the vectors differ in length. For modern string arrays enclosed in double quotes ("text"), both strcmp and == are supported, with == enabling familiar element-wise relational operations.

Does strcmp ignore trailing spaces?

No. strcmp treats whitespace as significant characters. A character vector with trailing blanks (such as 'control ') will not match an unpadded vector ('control'). Use strtrim to strip leading and trailing whitespace before comparison.

Can strcmp compare a single string against a full cell array?

Yes. When one argument is a scalar character vector or string and the other is a cell array of character vectors, strcmp compares the scalar against every cell element, returning a logical array matching the dimensions of the cell array.

Sources

Follow CASRAI

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

Ask CASRAI · free to try

Ask about MATLAB strcmp: Text Comparison Syntax & Rules

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 →