Mercurial > hg > octave-nkf
diff scripts/strings/str2num.m @ 13315:fa1b2b394195
str2num.m: Simplify and speed up code by using indexing.
* str2num.m: Use indexing instead of repmat and concatenation
for 8% speedup.
author | Rik <octave@nomad.inbox5.com> |
---|---|
date | Mon, 10 Oct 2011 21:04:22 -0700 |
parents | 89fb0e668825 |
children | 9de488c6c59c |
line wrap: on
line diff
--- a/scripts/strings/str2num.m +++ b/scripts/strings/str2num.m @@ -53,15 +53,12 @@ if (nargin != 1) print_usage (); - endif - - if (! ischar (s)) + elseif (! ischar (s)) error ("str2num: S must be a string or string array"); endif - [nr, nc] = size (s); - sep = repmat (";", nr, 1); - s = sprintf ("m = [%s];", reshape ([s, sep]', 1, nr * (nc + 1))); + s(:, end+1) = ";"; + s = sprintf ("m = [%s];", reshape (s', 1, numel (s))); state = true; eval (s, "m = []; state = false;"); if (ischar (m)) @@ -75,13 +72,14 @@ %!assert(str2num ("-1.3e2"), -130); %!assert(str2num ("[1, 2; 3, 4]"), [1, 2; 3, 4]); +%!test +%! [x, state] = str2num ("pi"); +%! assert (state); +%! [x, state] = str2num ("Hello World"); +%! assert (! state); + %% Test input validation %!error str2num () %!error str2num ("string", 1) -%!error str2num ({"string"}) +%!error <S must be a string> str2num ({"string"}) -%!test -%! [x, state] = str2num ("pi"); -%! assert (state); -%! [x, state] = str2num (tmpnam); -%! assert (! state);