Help with try catch and cellfun/eval
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello! I need to evaluate a cell with 9 cell arrays that include strings. Not all of them can be evaluated with "eval" (e.g. 'xyz'). This try-catch structure:
function c2 = func1(c1)
c2 = cell(size(c1));
msgID = 'MATLAB:inputError';
msgtext = 'Input does not have the expected format';
ME = MException(msgID,msgtext);
for k = 1:numel(c1)
try
c2{k} = {true,eval(c1{k}),[]};
catch ME
c2{k} = {false,c1{k},ME};
end
end
works perfectly.
Now I have to do the same with a local subfunction with cellfun and without a for loop. All I can think of is this subfunction:
function r = func_sub(str)
r = cellfun(@(x) eval(x), str, 'UniformOutput', false);
end
But how do I include this in a try-catch structure?
Thank you!
2 commentaires
Jan
le 3 Juil 2017
cellfun is an implicite loop. I do not see any benefit in avoiding the loop.
By the way: I'm convinced that the solution is ugly. Are you 100% sure, that the eval'ed strings do not contain a 'c1={}' or 'c2=rand'? A 'false=true' would be smart also.
Are you really really sure, that you want to eval and that a loop is not applicable?
Stephen23
le 4 Juil 2017
Modifié(e) : Stephen23
le 4 Juil 2017
'I need to evaluate a cell with 9 cell arrays that include strings. Not all of them can be evaluated with "eval"'
Is that really required? What you have described so far sounds like a very hacky, buggy, and insecure way to do something... but you have not told us what that something is. What is the actual task that you are trying to solve? If we knew more about the task then we might be able to help find a better way to do this.
You might like to read these and learn why using eval is not the panacea that some beginners think it is:
Réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!