time | calls | line |
---|
| | 1 | function [x,ok] = str2num(s)
|
| | 2 | %STR2NUM Convert string matrix to numeric array.
|
| | 3 | % X = STR2NUM(S) converts a character array representation of a matrix of
|
| | 4 | % numbers to a numeric matrix. For example,
|
| | 5 | %
|
| | 6 | % S = ['1 2' str2num(S) => [1 2;3 4]
|
| | 7 | % '3 4']
|
| | 8 | %
|
| | 9 | % The numbers in the string matrix S should be ASCII character
|
| | 10 | % representations of a numeric values. Each number may contain digits,
|
| | 11 | % a decimal point, a leading + or - sign, an 'e' or 'd' preceding a
|
| | 12 | % power of 10 scale factor, and an 'i' or 'j' for a complex unit.
|
| | 13 | %
|
| | 14 | % If the string S does not represent a valid number or matrix,
|
| | 15 | % STR2NUM(S) returns the empty matrix. [X,OK]=STR2NUM(S) will
|
| | 16 | % return OK=0 if the conversion failed.
|
| | 17 | %
|
| | 18 | % CAUTION: STR2NUM uses EVAL to convert the input argument, so side
|
| | 19 | % effects can occur if the string contains calls to functions. Use
|
| | 20 | % STR2DOUBLE to avoid such side effects or when S contains a single
|
| | 21 | % number.
|
| | 22 | %
|
| | 23 | % Also spaces can be significant. For instance, str2num('1+2i') and
|
| | 24 | % str2num('1 + 2i') produce x = 1+2i while str2num('1 +2i') produces
|
| | 25 | % x = [1 2i]. These problems are also avoided when you use STR2DOUBLE.
|
| | 26 | %
|
| | 27 | % See also STR2DOUBLE, NUM2STR, HEX2NUM, CHAR.
|
| | 28 |
|
| | 29 | % Copyright 1984-2007 The MathWorks, Inc.
|
| | 30 |
|
| 1 | 31 | if ~ischar(s) || ndims(s)>2
|
| | 32 | error(message('MATLAB:str2num:InvalidArgument'))
|
| | 33 | end
|
| | 34 |
|
| 1 | 35 | if isempty(s)
|
| | 36 | x = [];
|
| | 37 | ok=false;
|
| | 38 | return
|
| | 39 | end
|
| | 40 |
|
< 0.01 | 1 | 41 | [m,n] = size(s);
|
| 1 | 42 | if m==1,
|
| | 43 | % Replace any char(0) characters with spaces
|
| 1 | 44 | s(s==char(0)) = ' ';
|
| 1 | 45 | [x,ok] = protected_conversion(['[' s ']']); % Always add brackets
|
| | 46 | else
|
| | 47 | semi = ';';
|
| | 48 | space = ' ';
|
| | 49 | if ~any(any(s == '[' | s == ']')), % String does not contain brackets
|
| | 50 | o = ones(m-1,1);
|
| | 51 | s = [['[';space(o)] s [semi(o) space(o);' ]']]';
|
| | 52 | elseif ~any(any(s(1:m-1,:) == semi)), % No ;'s in non-last rows
|
| | 53 | s = [s,[semi(ones(m-1,1));space]]';
|
| | 54 | else % Put ;'s where appropriate
|
| | 55 | spost = space(ones(m,1));
|
| | 56 | for i = 1:m-1,
|
| | 57 | last = find(s(i,:) ~= space,1,'last');
|
| | 58 | if s(i,n-last+1) ~= semi,
|
| | 59 | spost(i) = semi;
|
| | 60 | end
|
| | 61 | end
|
| | 62 | s = [s,spost]';
|
| | 63 | end
|
| | 64 | [x,ok] = protected_conversion(s);
|
| | 65 | end
|
| 1 | 66 | if isnumeric(x)
|
| 1 | 67 | return
|
| | 68 | end
|
| | 69 | if ischar(x) || iscell(x)
|
| | 70 | x = [];
|
| | 71 | ok = false;
|
| | 72 | end
|