How to eval an expression without an error?

10 ビュー (過去 30 日間)
Mr M.
Mr M. 2018 年 10 月 16 日
回答済み: Andy Doller 2023 年 12 月 5 日
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.

回答 (2 件)

Guillaume
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

Andy Doller
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
did nothing

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by