strncmp — Compare text inputs for case-sensitive equality up to N leading characters with MATLAB-compatible broadcasting.
strncmp(A, B, N) compares corresponding text elements and returns logical true when the first N characters match exactly. It follows MATLAB-compatible case-sensitive comparison and implicit expansion behavior.
Syntax
tf = strncmp(A, B, N)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | First text input (string/char/cell/string array). |
B | Any | Yes | — | Second text input (string/char/cell/string array). |
N | IntegerScalar | Yes | — | Prefix length to compare. |
Returns
| Name | Type | Description |
|---|---|---|
tf | LogicalArray | Logical prefix-comparison result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:strncmp:InvalidInput | At least one text input is not a supported text container. | strncmp: text inputs must be string/char/cell/string-array values |
RunMat:strncmp:ShapeMismatch | Text inputs are not broadcast-compatible. | strncmp: input sizes are not broadcast-compatible |
RunMat:strncmp:InvalidPrefixLength | Prefix length argument is not a finite nonnegative integer scalar. | strncmp: prefix length must be a finite nonnegative integer scalar |
RunMat:strncmp:InternalError | Internal logical result assembly failed. | strncmp: internal error |
How strncmp works
- Accepted text types: String scalars/arrays, character vectors or character arrays, and cell arrays of character vectors.
- Scalar
Nrequirement: The third argument accepts double, single, or any of the eight integer classes as an integer scalar. It is read from native storage. - Implicit expansion: Scalars expand to match the size of the other operand before comparison.
- Character arrays: Rows are treated as independent character vectors. Each row is compared against the other operand and the result is returned as a column vector.
- Unicode-aware comparisons: Prefixes are counted in MATLAB characters (Unicode scalar values), so multi-byte UTF-8 sequences are handled transparently.
- Prefix length semantics: If
Nis zero or negative, every comparison evaluates totrue. If either text element is shorter thanN, it must match exactly up to the end of the shorter value and the longer value must also end withinNcharacters to be considered equal. - Missing strings: Any comparison involving a missing string returns
falseunlessN == 0. - Result type: Scalar comparisons return logical scalars. Array comparisons return logical arrays that follow MATLAB's column-major ordering.
- Unsupported datatypes: Integer and other numeric values in
AorBare unsupported text operands and return scalar logicalfalsewithout gather or implicit text conversion.
Does RunMat run strncmp on the GPU?
strncmp is a host comparison sink. RunMat may gather an admitted automatically resident numeric count through its owner, but unsupported resident numeric text operands return false before provider access.
GPU memory and residency
No. strncmp returns host logical output. Provider-resident numeric text operands are unsupported and return false without gather; an admitted automatically resident count may gather transparently.
Examples
Checking whether two strings share a prefix
tf = strncmp("RunMat", "Runway", 3)Expected output:
tf = logical
1Comparing string arrays with implicit expansion
names = ["north" "south" "east"];
tf = strncmp(names, "no", 2)Expected output:
tf = 1×3 logical array
1 0 0Comparing rows of a character array
animals = char("cat", "camel", "cow");
tf = strncmp(animals, "ca", 2)Expected output:
tf = 3×1 logical array
1
1
0Comparing cell arrays element-wise
C1 = {'red', 'green', 'blue'};
C2 = {'rose', 'grey', 'black'};
tf = strncmp(C1, C2, 2)Expected output:
tf = 1×3 logical array
1 0 0Handling zero-length comparisons
tf = strncmp("alpha", "omega", 0)Expected output:
tf = logical
1Using strncmp with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how strncmp changes the result.
Run a small strncmp example, explain the result, then change one input and compare the output.
FAQ
What argument types does strncmp accept?⌄
A and B accept string arrays, character vectors/arrays, and cell arrays of character vectors. N accepts double, single, or any integer class; negative N is treated as zero.
Is the comparison case-sensitive?⌄
Yes. Use strncmpi if you need a case-insensitive prefix comparison.
What happens when N is zero?⌄
The builtin returns true for every element because zero leading characters are compared.
How are shorter strings handled when N is larger than their length?⌄
The shorter value must match the longer value exactly for its entire length, and the longer value must not have additional characters within the first N positions. Otherwise the comparison returns false.
How are missing string values treated?⌄
Any comparison that involves a missing string returns false, except when N is zero (because no characters are compared).
Does strncmp produce logical results?⌄
Yes. Scalar comparisons yield logical scalars; array inputs produce logical arrays that follow MATLAB’s column-major ordering.
Related Strings functions
Core
blanks · char · compose · convertCharsToStrings · convertContainedStringsToChars · convertStringsToChars · genvarname · int2str · isletter · isspace · isStringScalar · isstrprop · mat2str · native2unicode · newline · num2str · sprintf · sscanf · str2double · str2num · strcmp · strcmpi · string · string.empty · strings · strlength · strncmpi · strtok · unicode2native
Text Analytics
addDependencyDetails · addEntityDetails · addLemmaDetails · addPartOfSpeechDetails · addSentenceDetails · addTypeDetails · bagOfNgrams · bagOfWords · cosineSimilarity · doc2sequence · encode · extractFileText · extractHTMLText · fastTextWordEmbedding · findElement · getAttribute · htmlTree · ind2word · isVocabularyWord · normalizeWords · readWordEmbedding · removeLongWords · removeShortWords · removeStopWords · removeWords · stopWords · tokenDetails · tokenizedDocument · trainWordEmbedding · vaderSentimentScores · vec2word · word2ind · word2vec · wordEncoding · writeWordEmbedding
Transform
append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · extractBetween · insertAfter · insertBefore · join · lower · pad · replace · replaceBetween · reverse · split · splitlines · strcat · strip · strjoin · strjust · strrep · strsplit · strtrim · upper
Search
contains · endsWith · matches · startsWith · strfind
Pattern
digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how strncmp is executed, line by line, in Rust.
- View the source for strncmp in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.