strfind — Locate starting indices of substring matches in text inputs with MATLAB-compatible output forms.
k = strfind(str, pattern) returns starting positions of each occurrence of pattern within str. It follows MATLAB-compatible behavior across character vectors, strings, and cell arrays of character vectors.
Syntax
idx = strfind(str, pat)
idx = strfind(str, pat, "ForceCellOutput", value)Inputs
str- Type
Any- Required
- Yes
- Description
- Text input (string/char/cell/string array).
pat- Type
Any- Required
- Yes
- Description
- Pattern text (string/char/cell/string array).
name- Type
StringScalar- Required
- Yes
- Default
"ForceCellOutput"- Description
- Option name (`"ForceCellOutput"`).
value- Type
Any- Required
- Yes
- Description
- Logical-ish option value controlling forced cell output.
Returns
idx- Type
Any- Description
- Match start indices as a numeric row vector or cell array of row vectors.
Errors
RunMat:strfind:InvalidInput- When
- Text or pattern input is not a supported text container.
- Message
strfind: text and pattern inputs must be text values
RunMat:strfind:InvalidOption- When
- ForceCellOutput option arguments are invalid or malformed.
- Message
strfind: invalid option arguments
RunMat:strfind:ShapeMismatch- When
- Text and pattern inputs are not broadcast-compatible.
- Message
strfind: input sizes are not broadcast-compatible
RunMat:strfind:InternalError- When
- Internal output assembly failed.
- Message
strfind: internal error
Behavior
Accepts text inputs as string scalars/arrays, character vectors/arrays, or cell arrays of character vectors. Mixed combinations are permitted.
Applies MATLAB-style implicit expansion when either argument is non-scalar.
Returns a numeric row vector when both inputs are scalar text (character vectors or string scalars) and 'ForceCellOutput' is false. If either input is a cell array or the broadcasted result contains multiple elements, the output is a cell array with the broadcasted shape, and each cell contains a row vector of double indices.
Pattern matches are case-sensitive and may overlap. For example, strfind("aaaa","aa") yields [1 2 3].
An empty pattern returns an empty index vector. Typed missing strings (displayed as <missing>) never match any pattern.
Specify 'ForceCellOutput', true or double 1 to always obtain a cell array, even for scalar inputs.
Typed integer ForceCellOutput values are available in RunMat mode behind a compatibility gate; MATLAB-compatible mode retains logical and double zero/one.
Placement and effects
Matching operates on host text. The builtin has no text GPU kernel or fusion form; numeric and resident text-role inputs reject before provider access. It may throw for malformed arguments and options, but does not mutate workspace state or access files, network, randomness, or time.
An unused result is still evaluated and discarded. Ordinary host-text distribution is distinct from distributed-input support for this builtin.
Examples
Find substring positions in a character vector
idx = strfind('abracadabra', 'abra')Expected output:
idx = [1 8]Locate overlapping matches
idx = strfind("aaaa", "aa")Expected output:
idx = [1 2 3]Return matches for each element of a string array
words = ["hydrogen"; "helium"; "lithium"];
idx = strfind(words, "i")Expected output:
idx = 3×1 cell array
{[]}
{[4]}
{[2 5]}Search with multiple patterns against one subject
idx = strfind("saturn", ["sat", "turn", "moon"])Expected output:
idx = 1×3 cell array
{[1]} {[3]} {[]}Force cell output for scalar inputs
idx = strfind('mission', 's', 'ForceCellOutput', true)Expected output:
idx = 1×1 cell array
{[3 4]}Handle empty patterns and missing strings
idxEmpty = strfind("abc", "");
idxMissing = strfind(string(missing), "abc")Expected output:
idxEmpty = [];
idxMissing = []Using strfind with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how strfind changes the result.
Run a small strfind example, explain the result, then change one input and compare the output.
FAQ
What types can I pass to strfind?⌄
Use string scalars/arrays, character vectors/arrays, or cell arrays of character vectors for either argument. Mixed combinations are allowed; MATLAB-style implicit expansion aligns the inputs automatically.
How are the results formatted?⌄
When both inputs are scalar text (character vectors or string scalars) and 'ForceCellOutput' is false, strfind returns a numeric row vector with the starting indices. In all other cases — for example, if either input is a cell array or the broadcasted size exceeds one element — the result is a cell array whose shape matches the broadcasted size, with each cell containing a row vector of doubles.
Do matches overlap?⌄
Yes. The builtin considers every occurrence of the pattern, including overlapping matches.
What happens with empty patterns?⌄
An empty pattern returns an empty index vector. A missing subject or pattern also produces no matches.
How do I always get a cell array?⌄
Supply 'ForceCellOutput', true. This mirrors MATLAB and is useful when you want consistent cell outputs regardless of input sizes.
Does strfind support case-insensitive matching?⌄
No. strfind is case-sensitive like MATLAB. Use contains, startsWith, or the regular expression functions when you need case-insensitive searches.
Related Strings functions
Search
contains · endsWith · matches · startsWith
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
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 · strncmp · strncmpi · strtok · unicode2native
Pattern
digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern
Source you can read
Every RunMat function's source is public. Read exactly how strfind is executed, line by line, in Rust.
- View the source for strfind in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.