Reputation: 30734
I would like to set a flag that determines whether or not debug-print statements actually print to the console:
s_verbose = 1;
global DBG
if s_verbose
DBG = @(varargin) fprintf(varargin);
else
DBG = @(varargin) 1; % need the 1 :|
end
However this fails:
>> DBG('42')
Error using fprintf
Invalid file identifier.
Use fopen to generate a valid file identifier.
>> fprintf('42')
42
Is there any clean way to accomplish this?
Upvotes: 0
Views: 367
Reputation: 24127
I often use a utility function like this:
function vfprintf(verbose, varargin)
% VFPRINTF Display output optionally depending on the level of verbosity.
%
% VFPRINTF(TF, ARGS) passes the arguments ARGS to the built-in MATLAB
% command |fprintf| if TF is logical true. If TF is logical false, VFPRINTF
% does nothing.
assert(islogical(verbose) && isscalar(verbose),...
'utils:InvalidVerbose',...
'VERBOSE must be logical true or false');
if verbose
fprintf(varargin{:});
end
You can then call vfprintf
instead of fprintf
. Put your verbose
variable as the first argument, with a value of true
or false
, and then follow with whatever arguments you would normally supply to fprintf
. If verbose
is true
, it will display, but if verbose
is false
, it will do nothing.
PS - even if you do this, I would try to avoid making verbose
a global variable if possible. It's not necessary.
Upvotes: 1