]> Creatis software - CreaPhase.git/blob - octave_packages/m/strings/str2num.m
update packages
[CreaPhase.git] / octave_packages / m / strings / str2num.m
1 ## Copyright (C) 1996-2012 Kurt Hornik
2 ##
3 ## This file is part of Octave.
4 ##
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.
9 ##
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.
14 ##
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/>.
18
19 ## -*- texinfo -*-
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
23 ## array).  Examples:
24 ##
25 ## @example
26 ## @group
27 ## str2num ("3.141596")
28 ##       @result{} 3.141596
29 ##
30 ## str2num (["1, 2, 3"; "4, 5, 6"])
31 ##       @result{} 1  2  3
32 ##          4  5  6
33 ## @end group
34 ## @end example
35 ##
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.
39 ##
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
43 ## conversion.
44 ##
45 ## For cell array of strings use @code{str2double}.  
46 ## @seealso{str2double, eval}
47 ## @end deftypefn
48
49 ## Author: jwe
50
51 function [m, state] = str2num (s)
52
53   if (nargin != 1) 
54     print_usage ();
55   elseif (! ischar (s))
56     error ("str2num: S must be a string or string array");
57   endif
58
59   s(:, end+1) = ";";
60   s = sprintf ("m = [%s];", reshape (s', 1, numel (s)));
61   state = true;
62   eval (s, "m = []; state = false;");
63   if (ischar (m))
64     m = [];
65     state = false;
66   endif
67
68 endfunction
69
70
71 %!assert(str2num ("-1.3e2"), -130);
72 %!assert(str2num ("[1, 2; 3, 4]"), [1, 2; 3, 4]);
73
74 %!test
75 %! [x, state] = str2num ("pi");
76 %! assert (state);
77 %! [x, state] = str2num ("Hello World");
78 %! assert (! state);
79
80 %% Test input validation
81 %!error str2num ()
82 %!error str2num ("string", 1)
83 %!error <S must be a string> str2num ({"string"})
84