Is there any other way to do the job without using eval?
Afficher commentaires plus anciens
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 commentaire
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 30 Déc 2012
T1 = regexprep(get(handles.A_edit,'String'), '\[|\]', ' ');
T2 = regexp(T1, '[,;\s]', 'split');
Acell = str2double(T2);
A = cell2mat(Acell);
11 commentaires
G A
le 30 Déc 2012
Walter Roberson
le 30 Déc 2012
Modifié(e) : Walter Roberson
le 30 Déc 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
le 31 Déc 2012
Modifié(e) : Walter Roberson
le 31 Déc 2012
Walter Roberson
le 31 Déc 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
le 31 Déc 2012
G A
le 31 Déc 2012
Walter Roberson
le 31 Déc 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
le 31 Déc 2012
G A
le 31 Déc 2012
Walter Roberson
le 31 Déc 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.
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!