Borrar filtros
Borrar filtros

How to execute only one of multiple redundant matlab functions?

2 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Guillaume
Guillaume el 8 de En. de 2015
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

Más respuestas (1)

Adam
Adam el 8 de En. de 2015
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

Categorías

Más información sobre File Name Construction en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by