function f = loadexcept(file,vars,mode) <file> is a string referring to a .mat file <vars> is a variable name or a cell vector of variable names to NOT load <mode> (optional) is 0 means load <file> into the base workspace (as well as into struct <f>) 1 means load <file> into struct <f> Default: 0. load <file>, excluding variables named by <vars>. example: x = 1; y = 2; save('temp.mat','x','y'); clear x y; loadexcept('temp.mat','x') ~exist('x','var') exist('y','var')
0001 function f = loadexcept(file,vars,mode) 0002 0003 % function f = loadexcept(file,vars,mode) 0004 % 0005 % <file> is a string referring to a .mat file 0006 % <vars> is a variable name or a cell vector of variable names to NOT load 0007 % <mode> (optional) is 0008 % 0 means load <file> into the base workspace (as well as into struct <f>) 0009 % 1 means load <file> into struct <f> 0010 % Default: 0. 0011 % 0012 % load <file>, excluding variables named by <vars>. 0013 % 0014 % example: 0015 % x = 1; y = 2; 0016 % save('temp.mat','x','y'); 0017 % clear x y; 0018 % loadexcept('temp.mat','x') 0019 % ~exist('x','var') 0020 % exist('y','var') 0021 0022 % input 0023 if ~exist('mode','var') || isempty(mode) 0024 mode = 0; 0025 end 0026 if ~iscell(vars) 0027 vars = {vars}; 0028 end 0029 0030 % figure out variable names 0031 varlist = whos('-file',file); 0032 varlist = cat(2,{varlist.name}); 0033 0034 % exclude the ones we don't want 0035 ok = cellfun(@(x) ~ismember(x,vars),varlist); 0036 varlist = varlist(ok); 0037 0038 % load in the data 0039 f = load(file,varlist{:}); 0040 0041 % deal 0042 switch mode 0043 case 0 0044 0045 % assign to caller's workspace 0046 for p=1:length(varlist) 0047 assignin('base',varlist{p},f.(varlist{p})); 0048 end 0049 0050 case 1 0051 0052 end