1 ## Copyright (C) 1996-2012 Kurt Hornik
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {@var{x} =} str2num (@var{s})
21 ## @deftypefnx {Function File} {[@var{x}, @var{state}] =} str2num (@var{s})
22 ## Convert the string (or character array) @var{s} to a number (or an
27 ## str2num ("3.141596")
30 ## str2num (["1, 2, 3"; "4, 5, 6"])
36 ## The optional second output, @var{state}, is logically true when the
37 ## conversion is successful. If the conversion fails the numeric output,
38 ## @var{x}, is empty and @var{state} is false.
40 ## @strong{Caution:} As @code{str2num} uses the @code{eval} function
41 ## to do the conversion, @code{str2num} will execute any code contained
42 ## in the string @var{s}. Use @code{str2double} for a safer and faster
45 ## For cell array of strings use @code{str2double}.
46 ## @seealso{str2double, eval}
51 function [m, state] = str2num (s)
56 error ("str2num: S must be a string or string array");
60 s = sprintf ("m = [%s];", reshape (s', 1, numel (s)));
62 eval (s, "m = []; state = false;");
71 %!assert(str2num ("-1.3e2"), -130);
72 %!assert(str2num ("[1, 2; 3, 4]"), [1, 2; 3, 4]);
75 %! [x, state] = str2num ("pi");
77 %! [x, state] = str2num ("Hello World");
80 %% Test input validation
82 %!error str2num ("string", 1)
83 %!error <S must be a string> str2num ({"string"})