sprintf
Format data into string or character vector
Syntax
Description
formats the data in arrays str = sprintf(formatSpec,A1,...,An)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.
[
returns an error message as a character vector when the operation is unsuccessful.
Otherwise, str,errmsg]
= sprintf(formatSpec,A1,...,An)errmsg is empty.
translates escape-character sequences in str = sprintf(literalText)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
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'
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.'
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."
Explicitly convert double-precision values to integers.
str = sprintf('%d',round(pi))str = '3'
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 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'
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
Format of the output fields, specified using formatting operators. formatSpec also can include ordinary text and special characters.
If formatSpec includes literal text representing escape characters, such as \n, then sprintf translates the escape characters.
formatSpec can be a character vector in single quotes, or a string
scalar.
Formatting Operator
A formatting operator starts with a percent sign, %, and ends with a conversion character. The conversion character is required. Optionally, you can specify identifier, flags, field width, precision, and subtype operators between % and the conversion character. (Spaces are invalid between operators and are shown here only for readability).

Conversion Character
This table shows conversion characters to format numeric and character data as text.
| Value Type | Conversion | Details |
|---|---|---|
Integer, signed |
| Base 10 |
Integer, unsigned |
| Base 10 |
| Base 8 (octal) | |
| Base 16 (hexadecimal), lowercase letters | |
| Same as | |
Floating-point number |
| Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.) |
| Exponential notation, such as | |
| Same as | |
| The more compact of | |
| The more compact of | |
Characters or strings |
| Single character |
| Character vector or string array. The type of the output text is the same as the type of |
Optional Operators
The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.
Identifier
Order for processing the function input arguments. Use the syntax
, wheren$nrepresents the positions of the other input arguments in the function call.Example:
('%3$s %2$s %1$s %2$s','A','B','C')prints input arguments'A','B','C'as follows:C B A B.Note: If an input argument is an array, you cannot use identifiers to specify particular array elements from that input argument.
Flags
'–'Left-justify.
Example:%-5.2f
Example:%-10s'+'Always print a sign character (+ or –) for any numeric value.
Example:%+5.2f
Right-justify text.
Example:%+10s' 'Insert a space before the value.
Example:% 5.2f'0'Pad to field width with zeros before the value.
Example:%05.2f'#'Modify selected numeric conversions:
For
%o,%x, or%X, print0,0x, or0Xprefix.For
%f,%e, or%E, print decimal point even when precision is 0.For
%gor%G, do not remove trailing zeros or decimal point.
Example:
%#5.0fField Width
Minimum number of characters to print. The field width operator can be a number, or an asterisk (
*) to refer to an input argument.When you specify
*as the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With*as the field width operator, you can print different values with different widths.Example: The input arguments
('%12d',intmax)are equivalent to('%*d',12,intmax).Example: The input arguments
('%*d',[2 10 5 100])return'10 100', with two spaces allocated for10and five spaces for100. As an alternative, you also can specify the field widths and values as multiple arguments, as in('%*d',2,10,5,100).The function pads to field width with spaces before the value unless otherwise specified by flags.
Precision
For
%f,%e, or%ENumber of digits to the right of the decimal point
Example:'%.4f'printspias'3.1416'For
%gor%GNumber of significant digits
Example:'%.4g'printspias'3.142'The precision operator can be a number, or an asterisk (
*) to refer to an argument.When you specify
*as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With*as the precision operator, you can print different values to different precisions.When you specify
*.*as field width and precision operators, you must specify field widths, precisions, and values as triplets.Example: The input arguments
('%.4f',pi)are equivalent to('%.*f',4,pi).Example: The input arguments
('%6.4f',pi)are equivalent to('%*.*f',6,4,pi).Example: The input arguments
('%*.*f',6,4,pi,9,6,exp(1))return'3.1416 2.718282', with9and6as the field width and precision for the output ofexp(1).Note
If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.
Subtypes
You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.
Input Value Type
Subtype and Conversion Character
Output Value Type
Floating-point number
%bxor%bX
%bo
%buDouble-precision hexadecimal, octal, or decimal value
Example:%bxprintspias400921fb54442d18%txor%tX
%to
%tuSingle-precision hexadecimal, octal, or decimal value
Example:%txprintspias40490fdb
Text Before or After Formatting Operators
formatSpec can also include additional text before a percent sign,
%, or after a conversion character. The text can be:
Ordinary text to print.
Special characters that you cannot enter as ordinary text. This table shows how to represent special characters in
formatSpec.Special Character
Representation
Single quotation mark
''Percent character
%%Backslash
\\Alarm
\aBackspace
\bForm feed
\fNew line
\nCarriage return
\rHorizontal tab
\tVertical tab
\vCharacter whose Unicode® numeric value can be represented by the hexadecimal number,
N\xNExample:
returnssprintf('\x5A')'Z'Character whose Unicode numeric value can be represented by the octal number,
N\NExample:
returnssprintf('\132')'Z'
Notable Behavior of Conversions with Formatting Operators
If you specify a value that does not fit the conversion, such as a non-integer numeric value for a text conversion, MATLAB® may override the specified conversion.
Example:
'%s'convertspito3.141593e+00.If you apply a text conversion (either
%cor%s) to integer values, MATLAB converts values that correspond to valid character codes to characters.Example:
'%s'converts[65 66 67]toABC.
Numeric, character, or string arrays.
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string
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
Formatted text, returned as a character vector or a string scalar. The
type of output matches the type of formatSpec.
Error message, returned as a character vector, when the operation is
unsuccessful. Otherwise, errmsg is empty.
Tips
The
sprintffunction is similar tofprintf, butfprintfprints to a file or to the Command Window.Format specifiers for the reading functions
sscanfandfscanfdiffer from the formats for the writing functionssprintfandfprintf. The reading functions do not support a precision field. The width field specifies a minimum for writing, but a maximum for reading.If you specify an invalid formatting operator or special character, then
sprintfprints all text up to the invalid operator or character and discards the rest.Example: If
formatSpecis'value = %z', thensprintfprints'value ='because%zis not a formatting operator.Example: If
formatSpecis'character \x99999 = %s', thensprintfprints'character'because\x99999is 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
Usage notes and limitations:
The
formatSpecparameter 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
sprintfcall in MATLAB at code generation time. In this case, the code generation restrictions forsprintfdo not apply and the behavior ofsprintfin 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 whensprintfis called inside aparforloop.The behavior of
sprintfin 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,
%eor%E.The
sprintfcall is inside aparforloop.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
sprintfwith 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
nis a double, code generation does not allow the following code:str = sprintf('%d',n)For code generation, first cast
nto a signed integer type such asint8.str = sprintf('%d',int8(n))When you call
sprintfwith 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.
The output of
sprintfin the generated C code might not match MATLAB output character by character. For example, MATLAB displaysInf, while the C code printsinf.
Refer to the usage notes and limitations in the C/C++ Code Generation section. The same usage notes and limitations apply to GPU code generation.
The sprintf function fully supports
thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
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).
The sprintf function
supports distributed arrays with these usage notes and limitations:
This function operates on distributed arrays, but executes on the client MATLAB.
For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).
Version History
Introduced before R2006a
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.
Sélectionner un site web
Choisissez un site web pour accéder au contenu traduit dans votre langue (lorsqu'il est disponible) et voir les événements et les offres locales. D’après votre position, nous vous recommandons de sélectionner la région suivante : .
Vous pouvez également sélectionner un site web dans la liste suivante :
Comment optimiser les performances du site
Pour optimiser les performances du site, sélectionnez la région Chine (en chinois ou en anglais). Les sites de MathWorks pour les autres pays ne sont pas optimisés pour les visites provenant de votre région.
Amériques
- 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
- United Kingdom (English)