Documentation Center

  • Trials
  • Product Updates

Formatting Strings

Functions that Use Format Strings

The following MATLAB® functions offer the capability to compose a string that includes ordinary text and data formatted to your specification:

  • sprintf — Write formatted data to an output string

  • 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

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 string, and %d means to format an integer using decimal notation.

The general formatting syntax for these functions is

functionname(..., format_string, value1, value2, ..., valueN)

where the format_string argument expresses the basic content and formatting of the final output string, and the value arguments that follow supply data values to be inserted into the string.

Here is a sample sprintf statement, also showing the resulting output string:

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 sprintf function to demonstrate how string formatting works. However, you can run the examples using the fprintf, warning, and error functions as well.

The Format String

The first input argument in the sprintf statement shown above is the format_string:

'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 for this particular string are: %s, %d, %d, %d, and %.2f.

Following the format_string argument are five additional input arguments, one for each of the formatting operators in the string:

'bread', 7, 1, 2006, 2.49

When MATLAB processes the format string, it replaces each operator with one of these input values.

Special Characters

Special characters are a part of the text in the string. 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 string.

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, N

\xN

Octal number, N

\N

Input Value Arguments

In the syntax

functionname(..., format_string, value1, value2, ..., valueN)

The value arguments must immediately follow format_string in the argument list. In most instances, you supply one of these value arguments for each formatting operator used in the format_string. 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 string:

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. The format_string needs one %s operator for the entire matrix or vector:

mvec = [77 65 84 76 65 66];

sprintf('%s ', char(mvec))
ans =
    MATLAB 

Sequential and Numbered Argument Specification

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 SequentiallyOrdered 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

The Formatting Operator

Formatting operators tell MATLAB how to format the numeric or character value arguments and where to insert them into the string. These operators control the notation, alignment, significant digits, field width, and other aspects of the output string.

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)

Constructing the Formatting Operator

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 String 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.

Conversion Character

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 as in 3.1415e+00)

E

Exponential notation (using an uppercase E as in 3.1415E+00)

f

Fixed-point notation

g

The more compact of %e or %f. (Insignificant zeros do not print.)

G

Same as %g, but using an uppercase E

o

Octal notation (unsigned)

s

String of characters

u

Decimal notation (unsigned)

x

Hexadecimal notation (using lowercase letters af)

X

Hexadecimal notation (using uppercase letters AF)

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

Subtype

The subtype field is a single alphabetic character that immediately precedes the conversion character. The following nonstandard subtype specifiers are supported for 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 '%bx'.

t

The underlying C data type is a float rather than an unsigned integer.

To specify the number of bits for the conversion of an integer value (corresponding to conversion characters %d, %i, %u, %o, %x, or %X), use one of the following subtypes.

l

64-bit value.

h

16-bit value.

Precision

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 strings (i.e., %s). If you do use it on a string and if the value p in the precision field is less than the number of characters in the string, MATLAB displays only p characters of the string 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 String for more information on this.

For more information on the use of precision in formatting, see Setting Field Width and Precision.

Field Width

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 string, the field width can determine whether MATLAB pads the string 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 String for more information on this.

For more information on the use of field width in formatting, see Setting Field Width and Precision.

Flags

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 –).

%+5.2d

A space ( )

Inserts a space before the value.

% 5.2f

Zero (0)

Pads with zeros rather than spaces.

%05.2f

A pound sign (#)

Modifies selected numeric conversions:

  • For %o, %x, or %X, print 0, 0x, or 0X prefix.

  • For %f, %e, or %E, print decimal point even when precision is 0.

  • For %g or %G, do not remove trailing zeros or decimal point.

%#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.

Value Identifiers

By default, MATLAB inserts data values from the argument list into the string 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 SequentiallyOrdered 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

Setting Field Width and Precision

This section provides further information on the use of the field width and precision fields of the formatting operator:

Effect on the Output String

The figure below illustrates the way in which the field width and precision settings affect the output of the string formatting functions. In this figure, the zero following the % sign in the formatting operator means to add leading zeros to the output string 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.

Specifying Field Width and Precision Outside the format String

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 string:

sprintf('%*.2f', 5, 123.45678)
ans =
    123.46

Using Identifiers In the Width and Precision Fields

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

Restrictions for Using Identifiers

If any of the formatting operators in a string include an identifier field, then all of the operators in that string must do the same; you cannot use both sequential and nonsequential ordering in the same function call.

Valid SyntaxInvalid 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 string, 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 SyntaxInvalid 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 SyntaxInvalid 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

Was this topic helpful?