Is there any other way to do the job without using eval?
Show older comments
Matlab experts say ' eval is evil'. I use eval in the case when I read Edit Text data in GUI and str2double is not applicable. For example, I need to type, read and save (in cell-array) an arbitrary array with arbitrary length, say A=[1,5,9]. I do:
set(handles.A_edit,'String','[1,5,9]')
C{1}=get(handles.A_edit,'String');
A=eval(C{1});
Is there any other way to do the job without using eval?
1 Comment
Accepted Answer
More Answers (1)
Walter Roberson
on 30 Dec 2012
T1 = regexprep(get(handles.A_edit,'String'), '\[|\]', ' ');
T2 = regexp(T1, '[,;\s]', 'split');
Acell = str2double(T2);
A = cell2mat(Acell);
11 Comments
G A
on 30 Dec 2012
Walter Roberson
on 30 Dec 2012
Edited: Walter Roberson
on 30 Dec 2012
Revised:
T1 = regexprep(get(handles.A_edit,'String'), '\[|\]', '');
T2 = regexp(T1, '[,;\s]', 'split');
A = str2double(T2);
This would need more work if you expected the user to be able to enter two-dimensional arrays instead of vectors.
G A
on 31 Dec 2012
Edited: Walter Roberson
on 31 Dec 2012
Walter Roberson
on 31 Dec 2012
if any(S == ':')
T2 = regexp(S, ':', 'split');
if length(T2) == 2 || (length(T2) == 3 & isempty(T2{2}))
T2(2:3) = {'1' T2{3}};
end
if length(T2) == 1
error('not enough roughage for colon')
elseif length(T2) == 3
A = str2double(T2{1}) : str2double(T2{2}) : str2double(T2{3});
else
error('too much roughage for colon')
end
else
%no colon to process
end
G A
on 31 Dec 2012
G A
on 31 Dec 2012
Walter Roberson
on 31 Dec 2012
Hmmm. Okay.
if length(T2) == 2
T2(2:3) = {'1' T2{2}}
elseif length(T2) == 3 & any(cellfun(@isempty, T2))
error('Cannot colonize empty fields.')
end
G A
on 31 Dec 2012
G A
on 31 Dec 2012
Walter Roberson
on 31 Dec 2012
T2 = regexp(T1, '[,;\s]+', 'split');
Note: with this modification, if the user enters (say) '[1,,,3]' then it would become [1 3] and the multiple delimiters would be ignored. If you want more error checking in the "no colon" section,
if regexp(S, '[\[,;\[]\s*[\[,;\[]')
error('multiple delimiters')
end
Mind you this will also reject '[[1],[2]]'. To do better, you need to define exactly which syntaxes you wish to permit.
Categories
Find more on Variables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!