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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
str | Any | Yes | — | Input text (string/char/cell). |
oldText | Any | Yes | — | Search text list (scalar or array/cell). |
newText | Any | Yes | — | Replacement text list (scalar or matching-size list). |
Returns
| Name | Type | Description |
|---|---|---|
newText | Any | Text with replacements applied, preserving input container kind. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:replace:InvalidInput | First argument is not a string array, char array, or cell array of text scalars. | replace: first argument must be a string array, character array, or cell array of character vectors |
RunMat:replace:PatternType | Second argument is not a text scalar/array/cell of text scalars. | replace: second argument must be a string array, character array, or cell array of character vectors |
RunMat:replace:ReplacementType | Third argument is not a text scalar/array/cell of text scalars. | replace: third argument must be a string array, character array, or cell array of character vectors |
RunMat:replace:EmptyPattern | Search text list is empty. | replace: second argument must contain at least one search string |
RunMat:replace:EmptyReplacement | Replacement text list is empty. | replace: third argument must contain at least one replacement string |
RunMat:replace:SizeMismatch | Replacement list is neither scalar nor equal in length to search list. | replace: replacement array must be a scalar or match the number of search strings |
RunMat:replace:CellElement | Cell arrays contain non-text elements or non-row char arrays. | replace: cell array elements must be string scalars or character vectors |
RunMat:replace:InternalError | Internal output container construction failed. | replace: internal error |
How replace works
- String scalars remain strings. Missing string scalars (
<missing>) propagate unchanged. - 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
oldandnewinputs can be string scalars, string arrays, character arrays, or cell arrays of character vectors / strings.newmust be a scalar or match the number of search terms inold. - Non-text inputs (numeric, logical, structs, GPU tensors, etc.) produce MATLAB-compatible errors.
Does RunMat run replace on the GPU?
replace executes on the CPU. The builtin registers as an Accelerate sink, so the fusion planner never attempts to keep results on the device. When any argument is GPU-resident, RunMat gathers it to host memory before performing replacements. Providers do not need special kernels for this builtin, and GPU-resident results are returned on the host.
GPU memory and residency
No. replace automatically gathers GPU inputs back to the host when necessary. Because it is marked with a gather-immediately residency policy, both inputs and outputs live on the CPU, so you never have to move text values manually. This mirrors MATLAB behaviour where string manipulation runs on the CPU.
Examples
Replace all instances of a word in a string
txt = "RunMat accelerates MATLAB code";
result = replace(txt, "RunMat", "RunMat Accelerate")Expected output:
result = "RunMat Accelerate accelerates MATLAB code"Replace multiple terms in a string array
labels = ["GPU pipeline"; "CPU pipeline"];
result = replace(labels, ["GPU", "CPU"], ["Device", "Host"])Expected output:
result = 2×1 string
"Device pipeline"
"Host pipeline"Replace substrings in a character array while preserving padding
chars = char("alpha", "beta ");
out = replace(chars, "a", "A")Expected output:
out =
2×5 char array
'AlphA'
'betA 'Replace text within a cell array of character vectors
C = {'Kernel Fusion', 'GPU Planner'};
updated = replace(C, {'Kernel', 'GPU'}, {'Shader', 'Device'})Expected output:
updated = 1×2 cell array
{'Shader Fusion'} {'Device Planner'}Remove substrings by replacing with empty text
paths = ["runmat/bin", "runmat/lib"];
clean = replace(paths, "runmat/", "")Expected output:
clean = 1×2 string
"bin" "lib"Replace using scalar replacement for multiple search terms
message = "OpenCL or CUDA or Vulkan";
unified = replace(message, ["OpenCL", "CUDA", "Vulkan"], "GPU backend")Expected output:
unified = "GPU backend or GPU backend or GPU backend"Replace text stored inside a cell array of strings
cells = { "Snapshot", "VM Interpreter" };
renamed = replace(cells, " ", "_")Expected output:
renamed = 1×2 cell array
{"Snapshot"} {"VM_Interpreter"}Preserve missing strings during replacement
vals = ["runmat", "<missing>", "accelerate"];
out = replace(vals, "runmat", "RunMat")Expected output:
out = 1×3 string
"RunMat" <missing> "accelerate"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?⌄
Missing string scalars (<missing>) propagate unchanged. Replacements never convert a missing value into a non-missing string.
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?⌄
RunMat gathers GPU-resident inputs to host memory before performing replacements. The resulting value is returned on the host. Providers do not need to implement a GPU kernel for this builtin.
Related Strings functions
Transform
erase · eraseBetween · extractBetween · join · lower · pad · split · strcat · strip · strjoin · strrep · strsplit · strtrim · upper
Core
char · compose · num2str · sprintf · str2double · strcmp · strcmpi · string · string.empty · strings · strlength · strncmp
Search
contains · endsWith · startsWith · strfind
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. 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 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.