replace — Replace substring occurrences in string, char, and cell-text data with MATLAB-compatible mapping behavior.
replace(str, old, new) substitutes every occurrence of old in str with new. It supports string scalars/arrays, character arrays, and cell arrays of text, including MATLAB-compatible multi-pattern replacement mapping.
Syntax
newText = replace(str, oldText, newText)Inputs
str- Type
Any- Required
- Yes
- Description
- Input text (string/char/cell).
oldText- Type
Any- Required
- Yes
- Description
- Search text list (scalar or array/cell).
newText- Type
Any- Required
- Yes
- Description
- Replacement text list (scalar or matching-size list).
Returns
newText- Type
Any- Description
- Text with replacements applied, preserving input container kind.
Errors
RunMat:replace:TooManyOutputs- When
- More than one output is requested.
- Message
replace: too many output arguments
RunMat:replace:InvalidInput- When
- First argument is not a string array, char array, or cell array of text scalars.
- Message
replace: first argument must be a string array, character array, or cell array of character vectors
RunMat:replace:PatternType- When
- Second argument is not a text scalar/array/cell of text scalars.
- Message
replace: second argument must be a string array, character array, or cell array of character vectors
Behavior
String scalars remain strings. Typed missing string scalars (displayed as <missing>) propagate unchanged; literal <missing> text remains ordinary text.
String arrays are processed element wise while preserving shape.
Character arrays are handled row by row. Rows expand or shrink as needed and are padded with spaces so the result remains a rectangular char array, just like MATLAB.
Cell arrays must contain string scalars or character vectors. The result is a cell array with the same size and element types mirrored after replacement.
The old and new inputs can be string scalars, string arrays, character arrays, or cell arrays of character vectors / strings. new must be a scalar or match the number of search terms in old.
Non-text inputs (numeric, logical, structs, GPU tensors, etc.) produce MATLAB-compatible errors.
Integer semantics: replace has no numeric input role. Numeric, logical, symbolic, and provider-resident values are rejected before gather or provider access.
Placement and effects
Replacement executes on host text. Numeric resident values are not text and reject before provider access.
This pure host operation may throw and may suspend at admitted gathers. It performs no callbacks, workspace/environment mutation, filesystem operations, randomness, or Clock reads. There is no GPU kernel, fusion route, or distributed support. VM and native calls share the canonical portable Runtime binding; these declarations are not execution evidence.
Host text remains on the CPU; numeric resident values are not converted to text or gathered as textual operands.
Replacement is a host-only fusion boundary. Unsupported resident numeric values reject before provider access; there is no device text kernel.
Current implementation frontier
Character arrays with non-singleton dimensions beyond two, including those inside cells and delimiter controls, reject before row extraction. String and cell array geometry follows the per-entry behavior described here.
Pattern objects are accepted in the search role. Replacements preserve string and cell shapes, including N-D cells; character rows may change width. Earlier GPU-gather prose was incorrect. General managed text allocation and independent MATLAB parity remain incomplete.
Examples
Replace all instances of a word in a string
txt = "RunMat accelerates MATLAB code";
result = replace(txt, "RunMat", "RunMat Accelerate")Replace multiple terms in a string array
labels = ["GPU pipeline"; "CPU pipeline"];
result = replace(labels, ["GPU", "CPU"], ["Device", "Host"])Replace substrings in a character array while preserving padding
chars = char("alpha", "beta ");
out = replace(chars, "a", "A")Replace text within a cell array of character vectors
C = {'Kernel Fusion', 'GPU Planner'};
updated = replace(C, {'Kernel', 'GPU'}, {'Shader', 'Device'})Remove substrings by replacing with empty text
paths = ["runmat/bin", "runmat/lib"];
clean = replace(paths, "runmat/", "")Replace using scalar replacement for multiple search terms
message = "OpenCL or CUDA or Vulkan";
unified = replace(message, ["OpenCL", "CUDA", "Vulkan"], "GPU backend")Replace text stored inside a cell array of strings
cells = { "Snapshot", "VM Interpreter" };
renamed = replace(cells, " ", "_")Preserve missing strings during replacement
vals = ["runmat", string(missing), "accelerate"];
out = replace(vals, "runmat", "RunMat")Using replace with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how replace changes the result.
Run a small replace example, explain the result, then change one input and compare the output.
FAQ
What sizes are allowed for old and new inputs?⌄
old must contain at least one search term. new may be a scalar or contain the same number of elements as old. Otherwise, replace raises a size-mismatch error matching MATLAB behaviour.
Does replace modify the original input?⌄
No. The builtin returns a new value with substitutions applied. The original inputs are left untouched.
How are character arrays padded after replacement?⌄
Each row is expanded or truncated according to the longest resulting row. Shorter rows are padded with space characters so the output remains a proper char matrix.
How are missing strings handled?⌄
Typed missing string scalars propagate unchanged. Replacements never convert a missing value into a non-missing string; literal <missing> text remains ordinary text.
Can I replace with an empty string?⌄
Yes. Provide "" (empty string) or '' as the replacement to remove matched substrings entirely.
Does replace support overlapping matches?⌄
Replacements are non-overlapping and proceed from left to right, matching MATLAB’s behaviour for replace.
How does replace behave with GPU data?⌄
There is no GPU text representation or kernel. Numeric resident operands reject before provider access. The result is host text.
Related Strings functions
Transform
append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · extractBetween · insertAfter · insertBefore · join · lower · pad · replaceBetween · reverse · split · splitlines · strcat · strip · strjoin · strjust · strrep · strsplit · strtrim · upper
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
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
Search
contains · endsWith · matches · startsWith · strfind
Pattern
digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern
Source you can read
Every RunMat function's source is public. Read exactly how replace is executed, line by line, in Rust.
- View the source for replace 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.