pad — Pad text values to target lengths with MATLAB-compatible direction and fill-character options.
pad extends string/char/cellstr text values to requested lengths by adding fill characters on left, right, or both sides, using MATLAB-compatible defaults and option parsing.
Syntax
out = pad(str)
out = pad(str, len)
out = pad(str, direction)
out = pad(str, padCharacter)
out = pad(str, len, direction)
out = pad(str, len, padCharacter)
out = pad(str, direction, padCharacter)
out = pad(str, len, direction, padCharacter)Inputs
str- Type
Any- Required
- Yes
- Description
- Input text (string/char/cell).
len- Type
IntegerScalar- Required
- Yes
- Description
- Target length (non-negative integer).
direction- Type
StringScalar- Required
- Yes
- Default
"right"- Description
- Padding direction (`"left"|"right"|"both"`).
padCharacter- Type
StringScalar- Required
- Yes
- Default
" "- Description
- Single-character padding value.
Returns
out- Type
Any- Description
- Padded text preserving input container kind and shape.
Errors
RunMat:pad:TooManyOutputs- When
- More than one output is requested.
- Message
pad: too many output arguments
RunMat:pad:InvalidInput- When
- First argument is not a string array, char array, or cell array of text scalars.
- Message
pad: first argument must be a string array, character array, or cell array of character vectors
RunMat:pad:Length- When
- Length argument is not a non-negative integer scalar.
- Message
pad: target length must be a non-negative integer scalar
Behavior
Without a target length, pad extends each element to match the longest text in the input.
Providing a nonnegative scalar target guarantees a minimum length; single, double, and all eight integer classes are accepted from authoritative native storage, and existing text that already meets or exceeds the target is returned unchanged.
Direction keywords ('left', 'right', 'both') are case-insensitive; 'right' is the default. When an odd number of pad characters is required for 'both', the extra character is appended to the end.
padChar must be a single character (string scalar or 1×1 char array). The default is a space.
Character arrays remain rectangular. Each row is padded independently and then widened with spaces so the array keeps MATLAB’s column-major layout.
Cell arrays preserve their structure. Elements must be string scalars or 1×N character vectors and are padded while keeping their original type.
Missing strings (string(missing)) pass through unchanged. Zero-row character arrays, including those inside cells, retain their original owner and full shape even with a positive target. A one-row empty character vector is padded like any other row.
Placement and effects
Text inputs are host-only. Automatically placed numeric length controls gather transparently; explicit gpuArray length controls are unsupported.
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.
Text data is host-only. Automatically placed numeric length controls gather transparently; explicit gpuArray length controls reject before gather.
pad executes on the CPU. Numeric resident values in the text role reject without provider access, while an admitted automatic length control gathers through its owning provider.
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.
Target lengths use exact native integer parsing. String and cell shapes are preserved, including N-D cells. Typed missing strings are distinct from literal text. General managed text allocation and cross-backend parity remain unqualified.
Examples
Pad Strings To A Common Width
labels = ["GPU"; "Accelerate"; "RunMat"];
aligned = pad(labels)Pad Strings On The Left With Zeros
ids = ["42"; "7"; "512"];
zero_padded = pad(ids, 4, 'left', '0')Center Text With Both-Sided Padding
titles = ["core"; "planner"];
centered = pad(titles, 10, 'both', '*')Pad Character Array Rows
chars = char("GPU", "RunMat");
out = pad(chars, 8)Pad A Cell Array Of Character Vectors
C = {'solver', "planner", 'jit'};
cell_out = pad(C, 'right', '.')Leave Missing Strings Unchanged
values = ["RunMat", string(missing), "GPU"];
kept = pad(values, 8)Using pad with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how pad changes the result.
Run a small pad example, explain the result, then change one input and compare the output.
FAQ
What inputs does pad accept?⌄
String scalars, string arrays, character arrays, and cell arrays containing string scalars or character vectors. Other types raise MATLAB-compatible errors.
How are direction keywords interpreted?⌄
'left', 'right', and 'both' are supported (case-insensitive). 'right' is the default. With 'both', extra characters are added to the end when an odd number of padding characters is required.
Can I shorten text with pad?⌄
No. When the existing text is already longer than the requested target length, it is returned unchanged.
What happens when I supply a custom padding character?⌄
The character must be length one. RunMat repeats it as many times as needed in the specified direction.
Do missing strings get padded?⌄
Typed missing strings (displayed as <missing>) are passed through untouched so downstream code that checks for missing values continues to work.
How are cell array elements returned?⌄
Each cell retains its type: string scalars remain strings and character vectors remain 1×N character arrays after padding.
Does pad change the orientation of row or column string arrays?⌄
No. The shape of the input array is preserved exactly; only element lengths change.
Will pad run on the GPU in the future?⌄
The text operation is host-only. Automatically placed numeric length controls gather transparently, while explicit gpuArray length controls reject.
Related Strings functions
Transform
append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · extractBetween · insertAfter · insertBefore · join · lower · replace · 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 pad is executed, line by line, in Rust.
- View the source for pad 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.