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
num2strdoes not accept positional identifiers in theformatSpecinput 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
num2strprints all text up to the invalid operator or character and discards the rest.Example: If
formatSpecis'value = %z', thennum2strprints'value ='because%zis not a formatting operator.Example: If
formatSpecis'character \x99999 = %s', thennum2strprints'character'because\x99999is not a valid special character.It is recommended to use
mat2strwhen 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.5newstr =
"The value is 4.5" |
