sprintf - Format data into string or character vector - MATLAB (original) (raw)

Format data into string or character vector

Syntax

Description

[str](#btf%5Fbfy-1-str) = sprintf([formatSpec](#btf%5Fbfy-1%5Fsep%5Fshared-formatSpec),[A1,...,An](#btf%5Fbfy-1-A1An)) 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. IfformatSpec is a string, then so is the outputstr. 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](#btf%5Fbfy-1-str),[errmsg](#btf%5Fbfy-1-errmsg)] = sprintf([formatSpec](#btf%5Fbfy-1%5Fsep%5Fshared-formatSpec),[A1,...,An](#btf%5Fbfy-1-A1An)) returns an error message as a character vector when the operation is unsuccessful. Otherwise, errmsg is empty.

[str](#btf%5Fbfy-1-str) = sprintf([literalText](#mw%5Fa3407b4a-ecd8-440c-8c6e-effdd20eb2c2)) 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

Format a floating-point number using %e, %f, and %g specifiers.

A = 1/eps; str_e = sprintf('%0.5e',A)

str_f = sprintf('%0.5f',A)

str_f = '4503599627370496.00000'

str_g = sprintf('%0.5g',A)

Literal Text and Array Inputs

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

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

Explicitly convert double-precision values to integers.

str = sprintf('%d',round(pi))

Specify Field Width of a Printed Value

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$)

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)

Create Character Vector from Values in Cell Array

C = { 1, 2, 3 ; 'AA','BB','CC'};

str = sprintf(' %d %s',C{:})

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

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

Schematic of formatting operator characters.

Conversion Character

This table shows conversion characters to format numeric and character data as text.

Value Type Conversion Details
Integer, signed %d or %i Base 10
Integer, unsigned %u Base 10
%o Base 8 (octal)
%x Base 16 (hexadecimal), lowercase letters a–f
%X Same as %x, uppercase letters A–F
Floating-point number %f Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)
%e Exponential notation, such as 3.141593e+00 (Use a precision operator to specify the number of digits after the decimal point.)
%E Same as %e, but uppercase, such as 3.141593E+00 (Use a precision operator to specify the number of digits after the decimal point.)
%g The more compact of %e or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)
%G The more compact of %E or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)
Characters or strings %c Single character
%s Character vector or string array. The type of the output text is the same as the type of formatSpec.

Optional Operators

The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.

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:

Notable Behavior of Conversions with Formatting Operators

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

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:

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