How to execute only one of multiple redundant matlab functions?
4 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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
0 个评论
更多回答(1 个)
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
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!