Help with try catch and cellfun/eval

조회 수: 3 (최근 30일)
Sophie Anna
Sophie Anna 2017년 7월 3일
편집: Stephen23 2017년 7월 4일
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
Jan
Jan 2017년 7월 3일
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
Stephen23 2017년 7월 4일
편집: Stephen23 2017년 7월 4일
'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:

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by