The best of all worlds - disp + sprintf

| categories: matlab, octave | View Comments

Going through loops you would often find yourself writing something ugly like :

1: n=10;
2: is_verbose=true;
3: for i=1:n
4:  if(is_verbose)
5:   disp(sprintf('DBG: %d/%d',i,n));
6:  end
7:   % some interesting stuff here....
8: end
>> >> DBG: 1/10
DBG: 2/10
DBG: 3/10
DBG: 4/10
DBG: 5/10
DBG: 6/10
DBG: 7/10
DBG: 8/10
DBG: 9/10
DBG: 10/10
>>

While, if you had disp and sprintf combined, you could have written a beautiful code like this :

1: is_verbose=true;
2: n=10;
3: for i=1:n
4:  verbose_disp(is_verbose,'DBG: %d/%d',i,n);
5:  % some interesting stuff here....
6: end

Thanks to Matlab's varargin this little gem could be very close to sprintf in syntax.

 1: % purpose display only if the script is in verbose mode + include sprintf 
 2: % capabilities in disp.
 3: % syntax : verbose_disp(flag_verb,form,[variable_list])
 4: % flag_verb=1 if you want to display, and 0 if you don't want to
 5: % display
 6: % form = string including formatting directions for sprintf 
 7: % variable_list = more parameters which include variables fitting
 8: % into the format "form".
 9: %
10: % see also : disp, sprintf
11: 
12: % Copyright 2013 Avi Gozolchiani (http://tiny.cc/avigoz)
13: % This program is free software: you can redistribute it and/or modify
14: % it under the terms of the GNU General Public License as published by
15: % the Free Software Foundation, either version 3 of the License, or
16: % (at your option) any later version.
17: %
18: % This program is distributed in the hope that it will be useful,
19: % but WITHOUT ANY WARRANTY; without even the implied warranty of
20: % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21: % GNU General Public License for more details.
22: %
23: % You should have received a copy of the GNU General Public License
24: % along with this program.  If not, see <http://www.gnu.org/licenses/>.
25: 
26: % $Log$
27: function verbose_disp(flag_verb,form,varargin)
28: % little input checking
29: if(nargin<2)
30:     error('verbose_disp : wrong number of arguments');
31: end                                     % if(nargin<2)
32: if(~ischar(form))
33:     error('second argument should be a character string');
34: end                                 % if(~ischar(form))
35: % if mode=verbose display the formatted string
36: if(flag_verb)
37:   s=sprintf(form,varargin{:});
38:   disp(s);
39: end % if(flag_verb)

Copyright (C) 2015 by Avi Gozolchiani. See the License for information about copying.

org-mode source

blog comments powered by Disqus