How to execute only one of multiple redundant matlab functions?

조회 수: 4 (최근 30일)
Stefan
Stefan 2015년 1월 8일
답변: Guillaume 2015년 1월 8일
Dear reader,
Given a succession of multiple redundant commands, for example
cprintf('blue', '!! This is a message !!');
disp('!! This is a message !!');
I would like to be able to execute the first one of them and disregard the rest. However, assuming the file cprintf.m is not available on the system, matlab will issue an error and this is precisely what I want to avoid. So, alternatively, I would like to execute the second line which represents the fallback solution, avoiding the error.
Given this scenario, here is my question: how can I achieve this?
I assume I need to write a function, let's call it alternatives.m which should take as arguments both previous functions:
alternatives('cprintf('blue', '!! This is a message !!')','disp('!! This is a message !!')')
but I wouldn't know how to write the code.

채택된 답변

Guillaume
Guillaume 2015년 1월 8일
Probably the easiest way is to use try ... catch statements. The alternative would be to use exists and co.
function alternatives(varargin)
for statement = varargin
try
eval(statement{1});
return;
catch
end
end
error('none of the statement succeeded');
end
But, rather than using statement strings for which you don't get syntax correction, I would use function handles, like this:
alternatives(@() cprintf('blue', '!! This is a message !!'), @() disp('!! This is a message !!'));
The code for the function is then:
function alternatives(varargin)
for statement = varargin
try
statement{1}();
return;
catch
end
end
error('none of the statement succeeded');
end

추가 답변 (1개)

Adam
Adam 2015년 1월 8일
try
cprintf('blue', '!! This is a message !!');
catch err
disp('!! This is a message !!');
end
should work, though you can extend it if you want to only catch certain errors such as cprintf not existing, etc.
That is why I put the 'err' variable there, from which you can get the error id and respond only to certain errors and rethrow in the case of others etc.
If you just want to catch all errors and always do the alternative code though you can just remove the unused 'err' variable

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by