load files from subdirectories
2 次查看(过去 30 天)
显示 更早的评论
I am trying to open file BG.mat, which is present in most of the subfolders. And i want to load contents of this file in workspace. I tried using the following code, its second last line is giving me problem. Any comments would be appreciated. Thanks
filetofind = 'BG.mat';
dirinfo = dir();
dirinfo(~[dirinfo.isdir]) = []; %remove non-directories
tf = ismember( {dirinfo.name}, {'.', '..'});
dirinfo(tf) = []; %remove current and parent directory.
numsubdir = length(dirinfo);
lastmod = inf * ones(numsubdir,1);
for K = 1 : numsubdir
subdirinfo = dir(fullfile(dirinfo(K).name, filetofind));
load subdirinfo.name
end
1 个评论
回答(2 个)
Jan
2013-3-5
编辑:Jan
2013-3-5
Although I have to guess the error message, this command does not do what you expect:
load subdirinfo.name
This loads the file 'subdirinfo.name', but you want to load the file, whose name is stored in this variable:
load(subdirinfo.name);
Some minutes ago I've mentioned, that the number of users suffering under the non-functional form of SAVE (and LOAD) is decreasing. But now this confusing feature hit another user.
Remark: Loading MAT files directly to the workspace might cause serious bugs. Imagine a MAT file contains a variable called 'dirinfo'. Then the program will fail with an error (if you are lucky), or perform unwanted actions. It is much safer to catch the output in an array or struct:
Data{k} = load(...)
2 个评论
Jan
2013-3-5
Nicer:
inf(numsubdir,1); % Instead of: inf * ones(numsubdir,1);
The load() command requires the full path of the MAT file, otherwise it searches in the current directory.
for K = 1 : numsubdir
load(fullfile(dirinfo(K).name, filetofind));
end
Lauryn Hoch
2018-5-14
Your use of ismember is returning folders that are only named . and .. (the current and parent directory). tf is a logical array with two 'true' elements and everything else is false, which means you are not searching through real folders to find your file.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!