Next: JSON data encoding/decoding, Previous: String encoding, Up: Converting Strings [Contents][Index]
5.4.2 Numerical Data and Strings ¶
Apart from the string concatenation functions (see Concatenating Strings)which cast numerical data to the corresponding UTF-8 encoded characters, thereare several functions that format numerical data as strings. mat2str
and num2str
convert real or complex matrices, while int2str
converts integer matrices. int2str
takes the real part of complexvalues and round fractional values to integer. A more flexible way to formatnumerical data as strings is the sprintf
function(see Formatted Output, sprintf).
- :
s =
mat2str(x, n)
¶ - :
s =
mat2str(x, n, "class")
¶ Format real, complex, and logical matrices as strings.
The returned string may be used to reconstruct the original matrix by usingthe
eval
function.The precision of the values is given by n. If n is a scalarthen both real and imaginary parts of the matrix are printed to the sameprecision. Otherwise
n(1)
defines the precision of the realpart andn(2)
defines the precision of the imaginary part.The default for n is 15.If the argument
"class"
is given then the class of x isincluded in the string in such a way thateval
will result in theconstruction of a matrix of the same class.mat2str ([ -1/3 + i/7; 1/3 - i/7 ], [4 2]) ⇒ "[-0.3333+0.14i;0.3333-0.14i]"mat2str ([ -1/3 +i/7; 1/3 -i/7 ], [4 2]) ⇒ "[-0.3333+0i 0+0.14i;0.3333+0i -0-0.14i]"mat2str (int16 ([1 -1]), "class") ⇒ "int16([1 -1])"mat2str (logical (eye (2))) ⇒ "[true false;false true]"isequal (x, eval (mat2str (x))) ⇒ 1
See also: sprintf, num2str, int2str.
- :
str =
num2str(x)
¶ - :
str =
num2str(x, precision)
¶ - :
str =
num2str(x, format)
¶ Convert a number (or array) to a string (or a character array).
The optional second argument may either give the number of significantdigits (precision) to be used in the output or a format templatestring (format) as in
sprintf
(see Formatted Output).num2str
can also process complex numbers.Examples:
num2str (123.456) ⇒ 123.456num2str (123.456, 4) ⇒ 123.5s = num2str ([1, 1.34; 3, 3.56], "%5.1f") ⇒ s = 1.0 1.3 3.0 3.6whos s ⇒ Variables in the current scope: Attr Name Size Bytes Class ==== ==== ==== ===== ===== s 2x8 16 char Total is 16 elements using 16 bytesnum2str (1.234 + 27.3i) ⇒ 1.234+27.3i
The
num2str
function is not very flexible. For better controlover the results, usesprintf
(see Formatted Output).Programming Notes:
For MATLAB compatibility, leading spaces are stripped before returningthe string.
Integers larger than
flintmax
may not be displayed correctly.For complex x, the format string may only contain one outputconversion specification and nothing else. Otherwise, results will beunpredictable.
Any optional format specified by the programmer is used withoutmodification. This is in contrast to MATLAB which tampers with theformat based on internal heuristics.
See also: sprintf, int2str, mat2str.
- :
str =
int2str(n)
¶ Convert an integer (or array of integers) to a string (or a characterarray).
int2str (123) ⇒ 123s = int2str ([1, 2, 3; 4, 5, 6]) ⇒ s = 1 2 3 4 5 6whos s ⇒ Variables in the current scope: Attr Name Size Bytes Class ==== ==== ==== ===== ===== s 2x7 14 char Total is 14 elements using 14 bytes
This function is not very flexible. For better control over theresults, use
sprintf
(see Formatted Output).Programming Notes:
Non-integers are rounded to integers before display. Only the real partof complex numbers is displayed.
See also: sprintf, num2str, mat2str.
- :
d =
str2double(str)
¶ Convert a string to a real or complex number.
The string must be in one of the following formats where a and b are realnumbers and the complex unit is
'i'
or'j'
:- a + bi
- a + b*i
- a + i*b
- bi + a
- b*i + a
- i*b + a
If present, a and/or b are of the form [+-]d[,.]d[[eE][+-]d] wherethe brackets indicate optional arguments and
'd'
indicates zero ormore digits. The special input valuesInf
,NaN
, andNA
are also accepted.str may be a character string, character matrix, or cell array. Forcharacter arrays the conversion is repeated for every row, and a double orcomplex array is returned. Empty rows in s are deleted and notreturned in the numeric array. For cell arrays each character stringelement is processed and a double or complex array of the same dimensions asstr is returned.
For unconvertible scalar or character string input
str2double
returnsa NaN. Similarly, for character array inputstr2double
returns aNaN for any row of s that could not be converted. For a cell array,str2double
returns a NaN for any element of s for whichconversion fails. Note that numeric elements in a mixed string/numericcell array are not strings and the conversion will fail for these elementsand return NaN.Programming Note:
str2double
can replacestr2num
, is moreefficient, and avoids the security risk of usingeval
on unknown data.See also: str2num.
- :
x =
str2num(s)
¶ - :
[x, state] =
str2num(s)
¶ Convert the string (or character array) s to a number (or an array).
Examples:
str2num ("3.141596") ⇒ 3.141596str2num (["1, 2, 3"; "4, 5, 6"]) ⇒ 1 2 3 4 5 6
The optional second output, state, is logically true when theconversion is successful. If the conversion fails the numeric output,x, is empty and state is false.
Caution: As
str2num
uses theeval
function to do theconversion,str2num
will execute any code contained in the strings. Usestr2double
for a safer and faster conversion.For cell array of strings use
str2double
.See also: str2double, eval.
- :
d =
bin2dec(str)
¶ Return the decimal number corresponding to the binary number representedby the string str.
For example:
bin2dec ("1110") ⇒ 14
Spaces are ignored during conversion and may be used to make the binarynumber more readable.
bin2dec ("1000 0001") ⇒ 129
If str is a string matrix, return a column vector with one convertednumber per row of str; Invalid rows evaluate to NaN.
If str is a cell array of strings, return a column vector with oneconverted number per cell element in str.
See also: dec2bin, base2dec, hex2dec.
- :
bstr =
dec2bin(d)
¶ - :
bstr =
dec2bin(d, len)
¶ Return a string of ones and zeros representing the conversion of the integerd to a binary number.
If d is a matrix or cell array, return a string matrix with one rowfor each element in d, padded with leading zeros to the width of thelargest value.
The optional second argument, len, specifies the minimum number ofdigits in the result.
For negative elements of d, return the binary value of the two’scomplement. The result is padded with leading ones to 8, 16, 32, or 64bits as appropriate for the magnitude of the input. Positive inputelements are padded with leading zeros to the same width.
Examples:
dec2bin (14) ⇒ "1110"dec2bin (-14) ⇒ "11110010"
Programming tip:
dec2bin
discards any fractional part of the input.If you need the fractional part to be converted too, calldec2base
with a nonzero number of decimal places. You can also usefix
orround
on fractional inputs to ensure predictable rounding behavior.See also: bin2dec, dec2base, dec2hex.
- :
hstr =
dec2hex(d)
¶ - :
hstr =
dec2hex(d, len)
¶ Return a string representing the conversion of the integer d to ahexadecimal (base16) number.
If d is negative, return the hexadecimal complement of d.
If d is a matrix or cell array, return a string matrix with one rowfor each element in d, padded with leading zeros to the width of thelargest value.
The optional second argument, len, specifies the minimum number ofdigits in the result.
Examples:
dec2hex (2748) ⇒ "ABC"dec2hex (-2) ⇒ "FE"
Programming tip:
dec2hex
discards any fractional part of the input.If you need the fractional part to be converted too, calldec2base
with a nonzero number of decimal places. You can also usefix
orround
on fractional inputs to ensure predictable rounding behavior.See also: hex2dec, dec2base, dec2bin.
- :
d =
hex2dec(str)
¶ Return the integer corresponding to the hexadecimal number represented bythe string str.
For example:
hex2dec ("12B") ⇒ 299hex2dec ("12b") ⇒ 299
If str is a string matrix, return a column vector with one convertednumber per row of str; Invalid rows evaluate to NaN.
If str is a cell array of strings, return a column vector with oneconverted number per cell element in str.
See also: dec2hex, base2dec, bin2dec.
- :
str =
dec2base(d, base)
¶ - :
str =
dec2base(d, base, len)
¶ - :
str =
dec2base(d, base, len, decimals)
¶ Return a string of symbols in base base corresponding to thevalue d.
dec2base (123, 3) ⇒ "11120"
If d is negative, then the result will represent d in complementnotation. For example, negative binary numbers are in twos-complement, andanalogously for other bases.
If d is a matrix or cell array, return a string matrix with one rowper element in d, padded with leading zeros to the width of thelargest value.
If base is a string then the characters of base are used asthe symbols for the digits of d. Whitespace (spaces, tabs, newlines,, etc.) may not be used as a symbol.
dec2base (123, "aei") ⇒ "eeeia"
The optional third argument, len, specifies the minimum number ofdigits in the integer part of the result. If this is omitted, then
dec2base
uses enough digits to accommodate the input.The optional fourth argument, decimals, specifies the number ofdigits to represent the fractional part of the input. If this is omitted,then it is set to zero, and
dec2base
returns an integer output forbackward compatibility.dec2base (100*pi, 16)⇒ "13A"dec2base (100*pi, 16, 4)⇒ "013A"dec2base (100*pi, 16, 4, 6)⇒ "013A.28C59D"dec2base (-100*pi, 16)⇒ "EC6"dec2base (-100*pi, 16, 4)⇒ "FEC6"dec2base (-100*pi, 16, 4, 6)⇒ "FEC5.D73A63"
Programming tip: When passing negative inputs to
dec2base
, it isbest to explicitly specify the length of the output required.See also: base2dec, dec2bin, dec2hex.
- :
d =
base2dec(str, base)
¶ Convert str from a string of digits in base base to a decimalinteger (base 10).
base2dec ("11120", 3) ⇒ 123
If str is a string matrix, return a column vector with one value perrow of str. If a row contains invalid symbols then the correspondingvalue will be NaN.
If str is a cell array of strings, return a column vector with onevalue per cell element in str.
If base is a string, the characters of base are used as thesymbols for the digits of str. Space (’ ’) may not be used as asymbol.
base2dec ("yyyzx", "xyz") ⇒ 123
See also: dec2base, bin2dec, hex2dec.
- :
s =
num2hex(n)
¶ - :
s =
num2hex(n, "cell")
¶ Convert a numeric array to an array of hexadecimal strings.
For example:
num2hex ([-1, 1, e, Inf])⇒ "bff0000000000000 3ff0000000000000 4005bf0a8b145769 7ff0000000000000"
If the argument n is a single precision number or vector, the returnedstring has a length of 8. For example:
num2hex (single ([-1, 1, e, Inf]))⇒ "bf800000 3f800000 402df854 7f800000"
With the optional second argument
"cell"
, return a cell array ofstrings instead of a character array.See also: hex2num, hex2dec, dec2hex.
- :
n =
hex2num(s)
¶ - :
n =
hex2num(s, class)
¶ Typecast a hexadecimal character array or cell array of strings to anarray of numbers.
By default, the input array is interpreted as a hexadecimal numberrepresenting a double precision value. If fewer than 16 characters aregiven the strings are right padded with
'0'
characters.Given a string matrix,
hex2num
treats each row as a separate number.hex2num (["4005bf0a8b145769"; "4024000000000000"]) ⇒ [2.7183; 10.000]
The optional second argument class may be used to cause the inputarray to be interpreted as a different value type. Possible values are
Option Characters "int8"
2 "uint8"
2 "int16"
4 "uint16"
4 "int32"
8 "uint32"
8 "int64"
16 "uint64"
16 "char"
2 "single"
8 "double"
16 For example:
hex2num (["402df854"; "41200000"], "single") ⇒ [2.7183; 10.000]
See also: num2hex, hex2dec, dec2hex.
- :
[a, …] =
strread(str)
¶ - :
[a, …] =
strread(str, format)
¶ - :
[a, …] =
strread(str, format, format_repeat)
¶ - :
[a, …] =
strread(str, format, prop1, value1, …)
¶ - :
[a, …] =
strread(str, format, format_repeat, prop1, value1, …)
¶ This function is obsolete. Use
textscan
instead.Read data from a string.
The string str is split into words that are repeatedly matched to thespecifiers in format. The first word is matched to the firstspecifier, the second to the second specifier and so forth. If there aremore words than specifiers, the process is repeated until all words havebeen processed.
The string format describes how the words in str should beparsed. It may contain any combination of the following specifiers:
%s
The word is parsed as a string.
%f
%n
The word is parsed as a number and converted to double.
%d
%u
The word is parsed as a number and converted to int32.
%*
%*f
%*s
The word is skipped.
For %s and %d, %f, %n, %u and the associated %*s … specifiers anoptional width can be specified as %Ns, etc. where N is an integer > 1.For %f, format specifiers like %N.Mf are allowed.
literals
In addition the format may contain literal character strings; these will beskipped during reading.
Parsed word corresponding to the first specifier are returned in the firstoutput argument and likewise for the rest of the specifiers.
By default, format is
"%f"
, meaning that numbers are read fromstr. This will do if str contains only numeric fields.For example, the string
str = "\Bunny Bugs 5.5\n\Duck Daffy -7.5e-5\n\Penguin Tux 6"
can be read using
[a, b, c] = strread (str, "%s %s %f");
Optional numeric argument format_repeat can be used for limiting thenumber of items read:
- -1
(default) read all of the string until the end.
- N
Read N times nargout items. 0 (zero) is an acceptable value forformat_repeat.
The behavior of
strread
can be changed via property-value pairs. Thefollowing properties are recognized:"commentstyle"
Parts of str are considered comments and will be skipped.value is the comment style and can be any of the following.
"shell"
Everything from#
characters to the nearest end-of-line is skipped."c"
Everything between/*
and*/
is skipped."c++"
Everything from//
characters to the nearest end-of-line is skipped."matlab"
Everything from%
characters to the nearest end-of-line is skipped.- user-supplied. Two options:(1) One string, or 1x1 cell string: Skip everything to the right of it;(2) 2x1 cell string array: Everything between the left and right stringsis skipped.
"delimiter"
Any character in value will be used to split str into words(default value = any whitespace). Note that whitespace is implicitly addedto the set of delimiter characters unless a
"%s"
format conversionspecifier is supplied; see"whitespace"
parameter below. The setof delimiter characters cannot be empty; if needed Octave substitutes aspace as delimiter."emptyvalue"
Value to return for empty numeric values in non-whitespace delimited data.The default is NaN. When the data type does not support NaN (int32 forexample), then default is zero.
"multipledelimsasone"
Treat a series of consecutive delimiters, without whitespace in between,as a single delimiter. Consecutive delimiter series need not be vertically
"aligned"
."treatasempty"
Treat single occurrences (surrounded by delimiters or whitespace) of thestring(s) in value as missing values.
"returnonerror"
If value true (1, default), ignore read errors and return normally.If false (0), return an error.
"whitespace"
Any character in value will be interpreted as whitespace and trimmed;the string defining whitespace must be enclosed in double quotes for properprocessing of special characters like
"\t"
. Ineach data field, multiple consecutive whitespace characters are collapsedinto one space and leading and trailing whitespace is removed. The defaultvalue for whitespace is"\b\r\n\t"
(note the space). Whitespace is always added to the set of delimitercharacters unless at least one"%s"
format conversion specifier issupplied; in that case only whitespace explicitly specified in"delimiter"
is retained as delimiter and removed from the set ofwhitespace characters. If whitespace characters are to be kept as-is (ine.g., strings), specify an empty value (i.e.,""
) for"whitespace"
; obviously, whitespace cannot be a delimiter then.
When the number of words in str doesn’t match an exact multiple ofthe number of format conversion specifiers, strread’s behavior depends onthe last character of str:
- last character =
"\n"
Data columns are padded with empty fields or NaN so that all columns haveequal length
- last character is not
"\n"
Data columns are not padded; strread returns columns of unequal length
See also: textscan, sscanf.