num2str
Convert numbers to character array
Description
Note
string
is recommended over
num2str
for combining numeric scalars with text. Use
the + operator to combine strings and numeric values for improved
readability. For additional information, see Alternative Functionality.
converts a numeric array into a character array that represents the numbers. The
output format depends on the magnitudes of the original values.
s
= num2str(A
)num2str
is useful for labeling and titling plots with
numeric values.
applies a format specified by s
= num2str(A
,formatSpec
)formatSpec
to all elements of
A
.
Note
If a format is specified, s
will not include spaces
between elements of A
. To include spaces, add one to the
format.
Examples
Input Arguments
Output Arguments
Tips
num2str
does not accept positional identifiers in theformatSpec
input argument. For example,num2str([14 15],'%2$X %1$o)
returns an error.Positional identifiers specify the order in which the formatting operator processes input arguments of the function, not the elements of an input array. When you call
num2str
, there is only one input argument that has numbers to convert.If you specify an invalid formatting operator or special character, then
num2str
prints all text up to the invalid operator or character and discards the rest.Example: If
formatSpec
is'value = %z'
, thennum2str
prints'value ='
because%z
is not a formatting operator.Example: If
formatSpec
is'character \x99999 = %s'
, thennum2str
prints'character'
because\x99999
is not a valid special character.It is recommended to use
mat2str
when converting numeric values to text as part of the input toeval
.
Algorithms
num2str
trims any leading spaces from a character array, even
when formatSpec
includes a space character flag. For example,
num2str(42.67,'% 10.2f')
returns a 1-by-5 character array
'42.67'
.
Alternative Functionality
Update code that makes use of num2str
to combine numeric scalars
with text to use string
instead. Numeric values can be
combined with strings using the +
operator. For example:
Not Recommended | Recommended |
---|---|
newstr = ['The value is ' num2str(4.5)] newstr = 'The value is 4.5' |
newstr = "The value is " + 4.5 newstr = "The value is 4.5" |
Extended Capabilities
Version History
Introduced before R2006a