Proper string conversion with implicit data type in MATLAB -
i have arbitrary strings shall converted suited data types (i.e. scalar double, double array or string), depending on content. str2num()
job when interpreting status
return value, function evaluates content of string which:
- causes
str2num('3-7')
-4 (double)
, want stick'3-7' (char array)
- is severe security issue, since can potentially execute code
one workaround use str2double()
, not end double arrays, scalars or strings. unfortunately, isstrprop()
not appropriate this.
example inputs (and outputs):
- '123.4' -> 123.4 (double scalar) [covered
str2double()
,str2num()
] - abc' -> 'abc' (char array) [inherently covered
str2double()
,str2num()
] - '123,456' -> [123, 456] (double array) [covered
str2num()
only] - '3-7' -> '3-7' (char array) [don't know how cover]
use str2double
, strsplit
:
c = {'123.4','abc','123,456','3-7'}; ii = 1:numel(c) cc = strsplit(c{ii},','); res = [str2double(cc)]; if isnan(res) res = c{ii}; end disp(res) disp(class(res)) disp('****************') end
shows:
123.4000 double **************** abc char **************** 123 456 double **************** 3-7 char ****************
Comments
Post a Comment