load files from subdirectories
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Réponses (2)
Jan
le 5 Mar 2013
Modifié(e) : Jan
le 5 Mar 2013
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 commentaires
Jan
le 5 Mar 2013
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
le 14 Mai 2018
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 commentaires
Voir également
Catégories
En savoir plus sur File Operations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!