I wrote a function to load mat-files with wildcards in them into a struct, by using dir
to catch the wildcards and then invoking load
. This is the function:
function S = loadw(varargin)
%LOADW Load variables from file into workspace, with wildcard (*) in file name
filename = varargin{1};
if(ismember('*', filename))
[pathstr, ~, ext] = fileparts(filename);
if(isempty(pathstr))
pathstr = '.';
end
if(~strcmp(ext, '.mat'))
filename = [filename '.mat'];
end
dirFiles = dir(filename);
if(isempty(dirFiles))
error(['Unable to read file ''' filename ''': no such file or directory.']);
elseif(numel(dirFiles) == 1)
varargin{1} = [pathstr filesep dirFiles(1).name];
S = load(varargin{:});
else
S = cell(numel(dirFiles), 1);
for iFile = 1:numel(dirFiles)
varargin{1} = [pathstr filesep dirFiles(iFile).name];
S{iFile} = load(varargin{:});
end
end
else
S = load(varargin{:});
end
This works well, however it can only load a file into a struct, and not into the caller workspace as load
does.
How can I modify this function to set the variables in the caller workspace?
I thought about using assignin
to do this but this means I first load the variables into the function workspace and then transfer them to the caller workspace. I would prefer a method that does not require declaring the variables twice. Is this possible without re-implementing load
? Or, perhaps, is there no overhead in declaring the variables twice, so that using assignin('caller',...)
would actually be an efficient solution?