sprintf — Format data into character vectors using MATLAB-compatible sprintf conversion specifiers.
sprintf(formatSpec, A1, ..., An) formats values into a character row vector. It supports MATLAB-compatible conversion flags, widths, precision controls, and column-major array traversal with automatic format repetition.
Syntax
txt = sprintf(formatSpec, A...)Inputs
formatSpec- Type
Any- Required
- Yes
- Description
- Format template text.
A...- Type
Any- Required
- Variadic
- Description
- Values substituted by conversion specifiers.
Returns
txt- Type
Any- Description
- Formatted character row vector output.
Errors
RunMat:sprintf:InvalidFormatSpec- When
- formatSpec is invalid or unsupported.
- Message
sprintf: invalid formatSpec
RunMat:sprintf:ArgumentMismatch- When
- Conversion specifier count does not match provided arguments.
- Message
sprintf: format arguments do not match conversion specifiers
RunMat:sprintf:InternalError- When
- Internal char-array construction failed.
- Message
sprintf: internal error
RunMat:sprintf:TooManyOutputs- When
- More than one output is requested.
- Message
sprintf: too many output arguments
Behavior
formatSpec must be text: a character row vector or string scalar. Cell arrays and multi-row character arrays are rejected.
Arguments can be numeric, logical, strings, character arrays, or cell arrays containing supported scalar types. Numeric inputs accept scalar, vector, or matrix shapes; elements are flattened in column-major order.
All eight integer classes are formatted directly from native storage, including full-width int64 and uint64 values that cannot be represented exactly as double.
Escape sequences such as \n, \t, \r, \f, \b, \a, \v, octal (\123), and hexadecimal (\x7F) are interpreted before formatting so that sprintf can build multi-line text easily.
Width and precision may be literal digits or drawn from the input list using * or .*. Star arguments must be scalar numerics and are consumed in order.
Floating %e/%E use signed, at-least-two-digit exponents. %g/%G precision counts significant digits and suppresses trailing fractional zeros; # retains the decimal point and significant trailing zeros. A finite floating value that cannot fit a signed integer conversion (fractional or out of range) uses scientific notation instead of truncation or clamping; RunMat retains the specified flags, width, and precision for that effective conversion.
Flags match MATLAB behaviour: - left-aligns, + forces a sign, space reserves a leading space for positive numbers, 0 enables zero padding, and # produces alternate forms for octal, hexadecimal, and binary outputs or preserves the decimal point in floating conversions.
%% emits a literal percent character without consuming arguments.
Complex inputs are formatted as scalar text (a+bi) when used with %s; numeric conversions expect real scalars.
Additional arguments beyond those required by the repeating format string raise an error to match MATLAB diagnostics.
Execution and placement
Formatting executes on the CPU. GPU tensors are gathered through their exact owning provider before substitution.
sprintf is a residency sink. When inputs include GPU tensors, RunMat gathers them back to host memory through each tensor's exact owning provider before executing the formatter. Formatting itself runs entirely on the CPU; an unavailable owner or failed transfer returns an error.
Examples
Formatting A Scalar Value
txt = sprintf('Value: %d', 42)Expected output:
txt =
'Value: 42'Formatting With Precision And Width
txt = sprintf('pi ~= %8.4f', pi)Expected output:
txt =
'pi ~= 3.1416'Combining Strings And Numbers
label = sprintf('Trial %02d: %.1f%% complete', 7, 84.95)Expected output:
label =
'Trial 07: 85.0% complete'Formatting Vector Inputs
data = [10 20 30];
txt = sprintf('%d ', data)Expected output:
txt =
'10 20 30 'Using Star Width/Precision Arguments
txt = sprintf('%*.*f %*.*f', 4, 2, 15.2, 6, 4, 0.001)Expected output:
txt =
'15.20 0.0010'Quoting Text With %s
names = ["Ada", "Grace"];
txt = sprintf('Hello, %s! ', names)Expected output:
txt =
'Hello, Ada! Hello, Grace! 'Formatting GPU-Resident Data
G = gpuArray([1.5 2.5 3.5]);
txt = sprintf('%.1f;', G)Expected output:
txt =
'1.5;2.5;3.5;'Creating Multi-line Text
message = sprintf('First line\nSecond line\t(indented)')Expected output:
message =
'First line
Second line (indented)'Using sprintf with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how sprintf changes the result.
Run a small sprintf example, explain the result, then change one input and compare the output.
FAQ
What happens if there are not enough input values for the format specifiers?⌄
RunMat raises sprintf: not enough input arguments for format specifier as soon as a placeholder cannot be satisfied. This matches MATLAB's error message.
How are additional values treated when the format string contains fewer specifiers?⌄
The format string repeats until all array elements are consumed. If the format string consumes no arguments (for example, it contains only literal text) and extra values remain, RunMat raises an error because MATLAB would also treat this as a mismatch.
Can I use star (*) width or precision arguments with arrays?⌄
Yes. Each * consumes the next scalar value from the input stream. When you provide arrays for width or precision, elements are read in column-major order the same way data arguments are.
Does sprintf support complex numbers?⌄
Complex values can be formatted with %s, which renders MATLAB's canonical a+bi text. Numeric conversions require real-valued inputs and raise an error for complex scalars.
Are logical values supported?⌄
Yes. Logical inputs are promoted to numeric (1 or 0) before formatting, so you can combine them with integer or floating-point conversions.
Does sprintf allocate string scalars?⌄
No. sprintf always returns a character row vector for MATLAB compatibility. Use string or compose if you need string scalars or string arrays.
Does GPU hardware change formatting behaviour?⌄
No. Formatting occurs on the CPU. When GPU tensors appear in the input list, RunMat gathers them to host memory before substitution so the results match MATLAB exactly.
How do I emit a literal percent sign?⌄
Use %% inside the format specification. The formatter converts %% into a single % without consuming an argument.
How are empty inputs handled?⌄
If all argument arrays are empty, sprintf returns an empty character array (1×0). If the format string itself is empty, the result is also empty.
What happens with multi-row character arrays?⌄
MATLAB requires formatSpec to be a row vector. RunMat follows the same rule: multi-row character arrays raise sprintf: formatSpec must be a character row vector or string scalar.
Related Strings functions
Core
blanks · char · compose · convertCharsToStrings · convertContainedStringsToChars · convertStringsToChars · genvarname · int2str · isletter · isspace · isStringScalar · isstrprop · mat2str · native2unicode · newline · num2str · sscanf · str2double · str2num · strcmp · strcmpi · string · string.empty · strings · strlength · strncmp · 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
Source you can read
Every RunMat function's source is public. Read exactly how sprintf is executed, line by line, in Rust.
- View the source for sprintf 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.