Format data into string or character vector
collapse all in page
Syntax
str = sprintf(formatSpec,A1,...,An)
[str,errmsg]= sprintf(formatSpec,A1,...,An)
str = sprintf(literalText)
Description
str = sprintf(formatSpec,A1,...,An)
formats the data in arrays A1,...,An
using the formatting operators specified by formatSpec
and returns the resulting text in str
. The sprintf
function formats the values in A1,...,An
in column order. If formatSpec
is a string, then so is the output str
. Otherwise, str
is a character vector.
To return multiple pieces of formatted text as a string array or a cell array of character vectors, use the compose
function.
example
[str,errmsg]= sprintf(formatSpec,A1,...,An)
returns an error message as a character vector when the operation is unsuccessful. Otherwise, errmsg
is empty.
str = sprintf(literalText)
translates escape-character sequences in literalText
, such as \n
and \t
. It returns all other characters unaltered. If literalText
contain a formatting operator (such as %f
), then str
discards it and all characters after.
Examples
collapse all
Floating-Point Formats
Open Live Script
Format a floating-point number using %e
, %f
, and %g
specifiers.
A = 1/eps;str_e = sprintf('%0.5e',A)
str_e = '4.50360e+15'
str_f = sprintf('%0.5f',A)
str_f = '4503599627370496.00000'
str_g = sprintf('%0.5g',A)
str_g = '4.5036e+15'
Literal Text and Array Inputs
Open Live Script
Combine literal text with array values to create a character vector.
formatSpec = 'The array is %dx%d.';A1 = 2;A2 = 3;str = sprintf(formatSpec,A1,A2)
str = 'The array is 2x3.'
Specify Formatted Text as String Array
Open Live Script
To return formatted text as a string, specify formatSpec
as a string instead of a character vector when you call the sprintf
function.
Convert data and return the result as a string.
formatSpec = "The current time is: %d:%d %s";A1 = 11;A2 = 20;A3 = 'a.m.';str = sprintf(formatSpec,A1,A2,A3)
str = "The current time is: 11:20 a.m."
Convert input string. Input arrays that contain text either can be character vectors or strings.
A1 = 2;A2 = 35;A3 = "p.m.";str = sprintf(formatSpec,A1,A2,A3)
str = "The current time is: 2:35 p.m."
Integer Format with Floating-Point Inputs
Open Live Script
Explicitly convert double-precision values to integers.
str = sprintf('%d',round(pi))
str = '3'
Specify Field Width of a Printed Value
Open Live Script
Specify the minimum width of the printed value.
str = sprintf('%025d',123456)
str = '0000000000000000000123456'
The 0
flag in the %025d
format specifier requests leading zeros in the output.
Reorder Inputs Using Position Identifier (n$)
Open Live Script
Reorder the input values using the n$
position identifier.
A1 = 'X';A2 = 'Y';A3 = 'Z';formatSpec = ' %3$s %2$s %1$s';str = sprintf(formatSpec,A1,A2,A3)
str = ' Z Y X'
Create Character Vector from Values in Cell Array
Open Live Script
C = { 1, 2, 3 ; 'AA','BB','CC'};str = sprintf(' %d %s',C{:})
str = ' 1 AA 2 BB 3 CC'
The syntax C{:}
creates a comma-separated list of arrays that contain the contents of each cell from C
in column order. For example, C{1}==1
and C{2}=='AA'
.
Input Arguments
collapse all
A1,...,An
— Numeric, character, or string arrays
arrays
Numeric, character, or string arrays.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
literalText
— Input text without formatting operators
character vector | string scalar
Input text without formatting operators, specified as a character vector or string scalar. sprintf
translates any escape-character sequences in literalText
.
Data Types: char
| string
Output Arguments
collapse all
str
— Formatted text
character vector | string scalar
Formatted text, returned as a character vector or a string scalar. The type of output matches the type of formatSpec
.
errmsg
— Error message
character vector
Error message, returned as a character vector, when the operation is unsuccessful. Otherwise, errmsg
is empty.
Tips
The
sprintf
function is similar tofprintf
, butfprintf
prints to a file or to the Command Window.Format specifiers for the reading functions
sscanf
andfscanf
differfrom the formats for the writing functionssprintf
andfprintf
.The reading functions do not support a precision field. The widthfield specifies a minimum for writing, but a maximum for reading.If you specify an invalid formatting operator or special character, then
sprintf
prints all text up to the invalid operator or character and discards the rest.Example: If
formatSpec
is'value = %z'
, thensprintf
prints'value ='
because%z
is not a formatting operator.Example: If
formatSpec
is'character \x99999 = %s'
, thensprintf
prints'character'
because\x99999
is not a valid special character.
References
[1] Kernighan, B. W., and D. M. Ritchie, The C Programming Language, Second Edition, Prentice-Hall, Inc., 1988.
[2] ANSI specification X3.159-1989: “Programming Language C,” ANSI, 1430 Broadway, New York, NY 10018.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
The
formatSpec
parameter must be constant.In
formatSpec
, hexadecimal numbers must be in the range [0 7F] and octal numbers must be in the range [0 177].If all the input arrays are constant, the code generator evaluates the
sprintf
call in MATLAB at compile time. In this case, the code generation restrictions forsprintf
do not apply and the behavior ofsprintf
in the generated code is the same as the behavior in MATLAB.If extrinsic calls are not possible, the code generator produces C code for
sprintf
. Extrinsic calls are not possible when extrinsic calls are disabled or whensprintf
is called inside aparfor
loop.The behavior of
sprintf
in the generated code matches the C compiler behavior instead of the MATLAB behavior in these cases:The format specifier has a corresponding C format specifier, for example,
%e
or%E
.The
sprintf
call is inside aparfor
loop.Extrinsic calls are disabled.
These options and capabilities are not supported:
The
n$
position identifier for reordering input valuesPrinting arrays
Using subtypes to print a floating-point number as its octal, decimal, or hexadecimal value
When you call
sprintf
with the format specifier%s
, you cannot put a null character in the middle of the input character vector. To write a null character, usesprintf(fid, '%c', char(0))
.Input argument types must match their format types. For example, if
n
is a double, code generation does not allow the following code:str = sprintf('%d',n)
For code generation, first cast
n
to a signed integer type such asint8
.str = sprintf('%d',int8(n))
When you call
sprintf
with an integer format specifier, the type of the integer argument must be a type that the target hardware can represent as a native C type. For example, if you callsprintf('%d', int64(n))
, then the target hardware must have a native C type that supports a 64-bit integer.Dynamic memory allocation must be enabled.
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
The sprintf
function supports GPU array input with these usage notes and limitations:
This function accepts GPU arrays, but does not run on a GPU.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced before R2006a
See Also
char | fprintf | int2str | num2str | sscanf | fscanf | compose | string
Topics
- Formatting Text
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom (English)
Contact your local office