Personally, I'd use str2num
(which is based on eval
if you read the documentation). However, another option is sym
. The Symbolic Math toolbox is based on eval
as well of course, but it has input validation to avoid the potential dangers you're worried about. It is very robust and simple to use for what you need:
a = '1/3';
a = double(sym(a))
This also handles converting cell arrays of strings to vectors and matrices gracefully:
a={'1/3','1/33','1/333'; ...
'2/3','2/33','2/333'};
a = double(sym(a))
The following unlikely input will return warnings and an error (and not delete a
in memory):
b = 'delete a';
a = double(sym(b))
Thus you may want to use a try
/catch
statement to gracefully handle cases when a user may provide invalid input:
try
Xs = double(sym(X));
catch err
if strcmp(err.id,'MATLAB:UndefinedFunction')
error('YourFunctionName:UnknownInput','Your helpful message here.');
else
rethrow(err);
end
end
You could equally replace the Xs = double(sym(X));
line with a call to str2num
.