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
Input Arguments
Output Arguments
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
differ from the formats for the writing functionssprintf
andfprintf
. 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
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
Version History
Introduced before R2006a