Convert character array to numeric array
x = str2num(str)
[x, status] = str2num('str')
Note
|
x = str2num(str)
converts str
,
a character representation of a numeric value, to a numeric representation. str2num
also
converts character arrays to numeric arrays. If the input argument
does not represent a valid number or matrix, str2num
(str
)
returns the empty matrix in x
.
Text that represents a number can contain one or more numbers
separated by spaces, commas, or semicolons, such as '
',
'5
10,11,12
', or '5,10;15,20
'.
In addition to numeric values and delimiters, input text can also
include a decimal point, leading + or - signs, the letter e
or d
preceding
a power of 10 scale factor, the letter i
or j
indicating
a complex or imaginary number, or true
or false
indicating
logical values.
The following table shows several examples of valid inputs to str2num
:
String Input | Numeric Output | Output Class |
---|---|---|
'500' | 500 | double |
'500 250 125 67' | 500 250 125 67 | 1-by-4 row vector of double |
'500; 250; 125; 62.5' | 500.0000 250.0000 125.0000 62.5000 | 4-by-1 column vector of double |
'1 23 6 21; 53:56' | 1 23 6 21 53 54 55 56 | 2-by-4 matrix of double |
'12e-3 5.9e-3' | 0.0120 0.0059 | 1-by-2 row vector of double |
'uint16(500)' | 500 | 16–bit unsigned integer |
'false true' | 0 1 | 1-by-2 row vector of logical |
Note:
|
If the input text does not represent a valid number or matrix, str2num(str)
returns
the empty matrix in x
.
[x, status] = str2num('str')
returns
the status of the conversion in logical status
,
where status
equals logical 1
(true
)
if the conversion succeeds, and logical 0
(false
)
otherwise.
Space characters can be significant. For instance, str2num('1+2i')
and str2num('1
+ 2i')
produce x = 1+2i
, while str2num('1
+2i')
produces x = [1 2i]
. You can avoid
these problems by using the str2double
function.
Input a character vector that represent a single number. The output is a scalar double:
A = str2num('500') A = 500 class(A) ans = double
Repeat this operation, but this time using an unsigned 16–bit integer:
A = str2num('uint16(500)') A = 500 class(A) ans = uint16
Try three different ways of specifying a row vector. Each returns the same answer:
str2num('2 4 6 8') % Separate with spaces. ans = 2 4 6 8 str2num('2,4,6,8') % Separate with commas. ans = 2 4 6 8 str2num('[2 4 6 8]') % Enclose in brackets. ans = 2 4 6 8
Note that the first two of these commands do not need the MATLAB® square
bracket operator to create a matrix. The str2num
function
inserts the brackets for you if they are needed.
Use a column vector this time:
str2num('2; 4; 6; 8') ans = 2 4 6 8
And now a 2-by-2 matrix:
str2num('2 4; 6 8') ans = 2 4 6 8
cast
| char
| hex2num
| num2str
| sparse
| special
characters | sscanf
| str2double