function save_except(varargin) %SAVE_EXCEPT Save current workspace to disk except variables stated % % Like SAVE, this command can be called using statement syntax % save_except filename var1 var2 ... % save_except filename -option1 var1 var2 ... -option2 % % ...or function syntax: % save_except('filename', 'var1', 'var2', ...) % save_except('filename', 'var1', 'var2', ..., '-option1', '-option2') % % All variables in the calling workspace *except* those specified will be saved % to disk. % % Options accepted by Matlab's save can be passed in any position, except % -regexp and -struct, which are not supported. Wildcards in the variable names % are also not supported. % % If the variables to exclude don't exist, this is silently ignored. % To force an error, pass the '-PEDANTIC' option. % Iain Murray, March 2009 if ~all(cellfun(@isstr, varargin)) error('All arguments must be strings'); end % Extract and separate arguments opts = {}; exclude_vars = {}; filename = ''; for arg_cell = varargin arg = arg_cell{:}; if arg(1) == '-' opts{end + 1} = arg; else if filename if ismember('*', arg) error('* wildcards are not supported'); end exclude_vars{end + 1} = arg; else filename = arg; end end end % Process options opts = lower(opts); if ismember('-regexp', opts) error('-regexp option not supported'); end if ismember('-struct', opts) error('-struct option not supported'); end pedantic = ismember('-pedantic', opts); opts = setdiff(opts, '-pedantic'); % Work out which variables to save ws = evalin('caller', 'whos'); all_vars = {ws.name}; if pedantic bad = exclude_vars(~ismember(exclude_vars, all_vars)); if length(bad) > 0 error(['Some variables to exclude do not exist: ', sprintf('%s, ', bad{:})]); end end vars = setdiff(all_vars, exclude_vars); % Drive Matlab's save command save_cmd = ['save(', argstr(filename, opts{:}, vars{:}), ')']; if isempty(vars) save_empty(); else evalin('caller', save_cmd); end function str = argstr(varargin) %ARGSTR convert string arguments into a single string for eval str = ''; if length(varargin) > 0 for a_cell = varargin str = [str 39 a_cell{:} 39 ', ']; end str = str(1:end-2); end function save_empty() % This function covers the corner case when all variables are excluded. % Do the same as Matlab's save when run on an empty workspace. eval(evalin('caller', 'save_cmd'));