Help with try catch and cellfun/eval
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Jan
il 3 Lug 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
il 4 Lug 2017
Modificato: Stephen23
il 4 Lug 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:
Risposte (0)
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!