How to eval an expression without an error?
조회 수: 6 (최근 30일)
이전 댓글 표시
I would like to eval an expression, for example eval('x=a+b;'); But in case of non-existing a or b, I dont want to get an error, just do nothing.
댓글 수: 0
답변 (2개)
Guillaume
2018년 10월 16일
Not withstanding that using eval is a really bad idea, if you do really want to do it and not stop on error, wrap it in a try statement.
try
eval('x=a+b');
end
I'd recommend you catch the error, to check that it is indeed due to a missing variable and not some syntax error in your eval:
try
eval('x=a+b');
catch mexc
if ~strcmp(mexc.identifier, 'MATLAB:UndefinedFunction') %the exception you get for undefined function or variable
rethrow(mexc); %not the error we expected, really error as something else happened
end
end
댓글 수: 0
Andy Doller
2023년 12월 5일
Why not use the test for variables to exist
if exist('a') && exist('b')
x = a + b;
else
disp('did nothing')
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!