The following MATLAB^{®} functions offer the capability to compose character vectors or string arrays that include ordinary text and data formatted to your specification:
compose
—
Write arrays of formatted data to an output string array
sprintf
—
Write formatted data to an output character vector or string scalar
fprintf
—
Write formatted data to an output file or the Command Window
warning
—
Display formatted data in a warning message
error
—
Display formatted data in an error message and abort
assert
—
Generate an error when a condition is violated
MException
— Capture error information
Note:
Starting in R2016b, use the |
The syntax of each of these functions includes formatting operators
similar to those used by the printf
function
in the C programming language. For example, %s
tells MATLAB to
interpret an input value as a character vector, and %d
means
to format an integer using decimal notation.
The general formatting syntax for these functions is
functionname(..., formatSpec, value1, value2, ..., valueN)
where the formatSpec
argument expresses the
basic content and formatting of the final output, and the value
arguments
that follow supply data values to be inserted into the character vector.
Here is a sample sprintf
statement, also
showing the resulting output:
sprintf('The price of %s on %d/%d/%d was $%.2f.', ... 'bread', 7, 1, 2006, 2.49) ans = The price of bread on 7/1/2006 was $2.49.
Note:
The examples in this section of the documentation use only the |
The first input argument in the sprintf
statement
shown above is the formatSpec
:
'The price of %s on %d/%d/%d was $%.2f.'
This argument can include ordinary text, formatting operators and, in some
cases, special characters.
The formatting operators in this example are: %s
, %d
, %d
, %d
,
and %.2f
.
Following the formatSpec
argument are five
additional input arguments, one for each of the formatting operators
in the character vector:
'bread', 7, 1, 2006, 2.49
When MATLAB processes the format specifier, it replaces each operator with one of these input values.
Special characters are a part of the text in the character vector. But, because they cannot be entered as ordinary text, they require a unique character sequence to represent them. Use any of the following character sequences to insert special characters into the output.
To Insert a . . . | Use . . . |
---|---|
Single quotation mark | '' |
Percent character | %% |
Backslash | \\ |
Alarm | \a |
Backspace | \b |
Form feed | \f |
New line | \n |
Carriage return | \r |
Horizontal tab | \t |
Vertical tab | \v |
Hexadecimal number, | \xN |
Octal number, | \N |
In the syntax
functionname(..., formatSpec, value1, value2, ..., valueN)
The value
arguments must immediately follow formatSpec
in
the argument list. In most instances, you supply one of these value
arguments
for each formatting operator used in the formatSpec
.
Scalars, vectors, and numeric and character arrays are valid value
arguments. You cannot use cell arrays or structures.
If you include fewer formatting operators than there are values to insert, MATLAB reuses the operators on the additional values. This example shows two formatting operators and six values to insert into the output text:
sprintf('%s = %d\n', 'A', 479, 'B', 352, 'C', 651) ans = A = 479 B = 352 C = 651
You can also specify multiple value
arguments
as a vector or matrix. formatSpec
needs one %s
operator
for the entire matrix or vector:
mvec = [77 65 84 76 65 66]; sprintf('%s ', char(mvec)) ans = MATLAB
You can place value
arguments in the argument
list either sequentially (that is, in the same order in which their
formatting operators appear in the string), or by identifier (adding
a number to each operator that identifies which value
argument
to replace it with). By default, MATLAB uses sequential ordering.
To specify arguments by a numeric identifier, add a positive
integer followed by a $
sign immediately after
the %
sign in the operator. Numbered argument specification
is explained in more detail under the topic Value Identifiers.
Ordered Sequentially | Ordered By Identifier |
---|---|
sprintf('%s %s %s', ... '1st', '2nd', '3rd') ans = 1st 2nd 3rd | sprintf('%3$s %2$s %1$s', ... '1st', '2nd', '3rd') ans = 3rd 2nd 1st |
Formatting operators tell MATLAB how to format the numeric or character value arguments and where to insert them into the output text. These operators control the notation, alignment, significant digits, field width, and other aspects of the output.
A formatting operator begins with a %
character,
which may be followed by a series of one or more numbers, characters,
or symbols, each playing a role in further defining the format of
the insertion value. The final entry in this series is a single conversion
character that MATLAB uses to define the notation
style for the inserted data. Conversion characters used in MATLAB are
based on those used by the printf
function in the
C programming language.
Here is a simple example showing five formatting variations for a common value:
A = pi*100*ones(1,5); sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A) ans = 314.159265 % Display in fixed-point notation (%f) 314.16 % Display 2 decimal digits (%.2f) +314.16 % Display + for positive numbers (%+.2f) 314.16 % Set width to 12 characters (%12.2f) 000000314.16 % Replace leading spaces with 0 (%012.2f)
The fields that make up a formatting operator in MATLAB are as shown here, in the order they appear from right to left in the operator. The rightmost field, the conversion character, is required; the five to the left of that are optional. Each of these fields is explained in a section below:
Conversion Character — Specifies the notation of the output.
Subtype — Further specifies any nonstandard types.
Precision — Sets the number of digits to display to the right of the decimal point, or the number of significant digits to display.
Field Width — Sets the minimum number of digits to display.
Flags — Controls the alignment, padding, and inclusion of plus or minus signs.
Value Identifiers — Map formatting operators to value input arguments. Use the identifier field when value arguments are not in a sequential order in the argument list.
Here is an example of a formatting operator that uses all six fields. (Space characters are not allowed in the operator. They are shown here only to improve readability of the figure).
An alternate syntax, that enables you to supply values for the field width and precision fields from values in the argument list, is shown below. See the section Specifying Field Width and Precision Outside the Format Specifier for information on when and how to use this syntax. (Again, space characters are shown only to improve readability of the figure.)
Each field of the formatting operator is described in the following
sections. These fields are covered as they appear going from right
to left in the formatting operator, starting with the Conversion
Character
and ending with the Identifier
field.
The conversion character specifies the notation of the output. It consists
of a single character and appears last in the format specifier. It
is the only required field of the format specifier other than the
leading %
character.
Specifier | Description |
---|---|
c | Single character |
d | Decimal notation (signed) |
e | Exponential notation (using a lowercase |
E | Exponential notation (using an uppercase |
f | Fixed-point notation |
g | The more compact of |
G | Same as |
o | Octal notation (unsigned) |
s | Character vector |
u | Decimal notation (unsigned) |
x | Hexadecimal notation (using lowercase letters |
X | Hexadecimal notation (using uppercase letters |
This example uses conversion characters to display the number 46 in decimal, fixed-point, exponential, and hexadecimal formats:
A = 46*ones(1,4); sprintf('%d %f %e %X', A) ans = 46 46.000000 4.600000e+01 2E
The subtype field is a single alphabetic character that immediately
precedes the conversion character. To convert a floating-point value
to its octal, decimal, or hexadecimal value, use one of following
subtype specifiers. These subtypes support the conversion characters %o
, %x
, %X
,
and %u
.
b | The underlying C data type is a double rather than an
unsigned integer. For example, to print a double-precision value in
hexadecimal, use a format like |
t | The underlying C data type is a float rather than an unsigned integer. |
precision
in a formatting operator is a nonnegative
integer that immediately follows a period. For example, the specifier %7.3f
,
has a precision
of 3. For the %g
specifier, precision
indicates
the number of significant digits to display. For the %f
, %e
,
and %E
specifiers, precision
indicates
how many digits to display to the right of the decimal point.
Here are some examples of how the precision
field
affects different types of notation:
sprintf('%g %.2g %f %.2f', pi*50*ones(1,4)) ans = 157.08 1.6e+02 157.079633 157.08
Precision is not usually used in format specifiers for character
vectors (i.e., %s
). If you do use it on a character
vector and if the value p
in the precision field
is less than the number of characters in the vector, MATLAB displays
only p
characters and truncates the rest.
You can also supply the value for a precision field from outside of the format specifier. See the section Specifying Field Width and Precision Outside the Format Specifier for more information on this.
For more information on the use of precision
in
formatting, see Setting Field Width and Precision.
Field width
in a formatting operator is a
nonnegative integer that tells MATLAB the minimum number of digits
or characters to use when formatting the corresponding input value.
For example, the specifier %7.3f
, has a width of
7.
Here are some examples of how the width
field
affects different types of notation:
sprintf('|%e|%15e|%f|%15f|', pi*50*ones(1,4)) ans = |1.570796e+02| 1.570796e+02|157.079633| 157.079633|
When used on a character vector, the field width
can
determine whether MATLAB pads the vector with spaces. If width
is
less than or equal to the number of characters in the string, it has
no effect.
sprintf('%30s', 'Pad left with spaces') ans = Pad left with spaces
You can also supply a value for field width
from
outside of the format specifier. See the section Specifying Field Width and Precision Outside the Format Specifier for
more information on this.
For more information on the use of field width
in
formatting, see Setting Field Width and Precision.
You can control the output using any of these optional flags:
Character | Description | Example |
---|---|---|
A minus sign ( | Left-justifies the converted argument in its field. | %-5.2d |
A plus sign ( | Always prints a sign character (+ or –). for numeric
values. | %+5.2d %+5s |
A space ( | Inserts a space before the value. | % 5.2f |
Zero ( | Pads with zeros rather than spaces. | %05.2f |
A pound sign ( | Modifies selected numeric conversions:
| %#5.0f |
Right- and left-justify the output. The default is to right-justify:
sprintf('right-justify: %12.2f\nleft-justify: %-12.2f', ... 12.3, 12.3) ans = right-justify: 12.30 left-justify: 12.30
Display a +
sign for positive numbers. The
default is to omit the +
sign:
sprintf('no sign: %12.2f\nsign: %+12.2f', ... 12.3, 12.3) ans = no sign: 12.30 sign: +12.30
Pad to the left with spaces or zeros. The default is to use space-padding:
sprintf('space-padded: %12.2f\nzero-padded: %012.2f', ... 5.2, 5.2) ans = space-padded: 5.20 zero-padded: 000000005.20
Note: You can specify more than one flag in a formatting operator. |
By default, MATLAB inserts data values from the argument
list into the output text in a sequential order. If you have a need
to use the value arguments in a nonsequential order, you can override
the default by using a numeric identifier in each format specifier.
Specify nonsequential arguments with an integer immediately following
the %
sign, followed by a $
sign.
Ordered Sequentially | Ordered By Identifier |
---|---|
sprintf('%s %s %s', ... '1st', '2nd', '3rd') ans = 1st 2nd 3rd | sprintf('%3$s %2$s %1$s', ... '1st', '2nd', '3rd') ans = 3rd 2nd 1st |
This section provides further information on the use of the field width and precision fields of the formatting operator:
The figure below illustrates the way in which the field width
and precision settings affect the output of the formatting functions.
In this figure, the zero following the %
sign in
the formatting operator means to add leading zeros to the output text
rather than space characters:
General rules for formatting
If precision is not specified, it defaults to 6.
If precision (p
) is less than the
number of digits in the fractional part of the input value (f
),
then only p
digits are shown to the right of the
decimal point in the output, and that fractional value is rounded.
If precision (p
) is greater than
the number of digits in the fractional part of the input value (f
),
then p
digits are shown to the right of the decimal
point in the output, and the fractional part is extended to the right
with p-f
zeros.
If field width is not specified, it defaults to precision
+
1 + the number of digits in the whole part of the input value.
If field width (w
) is greater than p
+1
plus the number of digits in the whole part of the input value (n
),
then the whole part of the output value is extended to the left with w-(n+1+p)
space
characters or zeros, depending on whether or not the zero
flag
is set in the Flags
field. The default is to extend
the whole part of the output with space characters.
To specify field width or precision using values from a sequential
argument list, use an asterisk (*
) in place of
the field width
or precision
field
of the formatting operator.
This example formats and displays three numbers. The formatting
operator for the first, %*f
, has an asterisk in
the field width location of the formatting operator, specifying that
just the field width, 15, is to be taken from the argument list. The
second operator, %.*f
puts the asterisk after the
decimal point meaning, that it is the precision that is to take its
value from the argument list. And the third operator, %*.*f
,
specifies both field width and precision in the argument list:
sprintf('%*f %.*f %*.*f', ... 15, 123.45678, ... % Width for 123.45678 is 15 3, 16.42837, ... % Precision for rand*20 is .3 6, 4, pi) % Width & Precision for pi is 6.4 ans = 123.456780 16.428 3.1416
You can mix the two styles. For example, this statement gets the field width from the argument list and the precision from the format specifier:
sprintf('%*.2f', 5, 123.45678) ans = 123.46
You can also derive field width and precision values from a
nonsequential (i.e., numbered) argument list. Inside the formatting
operator, specify field width
and/or precision
with
an asterisk followed by an identifier number, followed by a $
sign.
This example from the previous section shows how to obtain field width and precision from a sequential argument list:
sprintf('%*f %.*f %*.*f', ... 15, 123.45678, ... 3, 16.42837, ... 6, 4, pi) ans = 123.456780 16.428 3.1416
Here is an example of how to do the same thing using numbered ordering. Field width for the first output value is 15, precision for the second value is 3, and field width and precision for the third value is 6 and 4, respectively. If you specify field width or precision with identifiers, then you must specify the value with an identifier as well:
sprintf('%1$*4$f %2$.*5$f %3$*6$.*7$f', ... 123.45678, 16.42837, pi, 15, 3, 6, 4) ans = 123.456780 16.428 3.1416
If any of the formatting operators include an identifier field, then all of the operators in that format specifier must do the same; you cannot use both sequential and nonsequential ordering in the same function call.
Valid Syntax | Invalid Syntax |
---|---|
sprintf('%d %d %d %d', ... 1, 2, 3, 4) ans = 1 2 3 4 | sprintf('%d %3$d %d %d', ... 1, 2, 3, 4) ans = 1 |
If your command provides more value arguments than there are formatting operators in the format specifier, MATLAB reuses the operators. However, MATLAB allows this only for commands that use sequential ordering. You cannot reuse formatting operators when making a function call with numbered ordering of the value arguments.
Valid Syntax | Invalid Syntax |
---|---|
sprintf('%d', 1, 2, 3, 4) ans = 1234 | sprintf('%1$d', 1, 2, 3, 4) ans = 1 |
Also, do not use identifiers when the value arguments are in the form of a vector or array:
Valid Syntax | Invalid Syntax |
---|---|
v = [1.4 2.7 3.1]; sprintf('%.4f %.4f %.4f', v) ans = 1.4000 2.7000 3.1000 | v = [1.4 2.7 3.1]; sprintf('%3$.4f %1$.4f %2$.4f', v) ans = Empty string: 1-by-0 |