For loop to work on files in subfolders, while skipping the first file
1 次查看(过去 30 天)
显示 更早的评论
I want todecode my data with tdt on MATLAB. I have a folder, this folder has 70 sub-folders. Each of the 70 sub-folders has four .mat files. I want to work on the 2nd three files while loading the first spm.mat file separately. How do I write a for loop that runs through these files so that after working on the loading the first file, I can work on each of the other 3 files sequentially then move to the next folder. These 3 files start with the letters voi (e g voi 1, voi 2). I used the folowing and got an error message: Dot indexing is not supported for variables of this type.
folders = dir('parent folder path'); % Captures all contents of parent folder
folders = folders([folders(:).isdir]==1); % Filter to just folders
folders = folders(3:end); % Remove unnecessary '.' and '..' directories
for i = 1:length(folders)
path = [folders(i).folder,'\',folders(i).name]; % do work with path variable directing to each child folder.
end
end
2 个评论
Stephen23
2022-7-9
folders = folders(3:end); % Does NOT remove '.' and '..' directories
https://www.mathworks.com/matlabcentral/answers/1699230-folder-listing-with-dir-on-mac#answer_945260
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
采纳的回答
Image Analyst
2022-7-9
Here's one way:
topLevelFolder = pwd; % Wherever you want.
filePattern = fullfile(topLevelFolder, '**/*.*');
folders = dir(filePattern); % Captures all contents of parent folder and subfolders
% Filter to just folders
itsAFolder = [folders.isdir]
folders = folders(itsAFolder);
% Get all folder names in a cell array.
folderNames = {folders.folder, folders.name}'
c = contains(folderNames, topLevelFolder)
folderNames = unique(folderNames(c))
% Loop over each folder and subfolder.
for k = 1:length(folderNames)
thisFolder = folderNames{k};
fprintf('Processing folder : "%s".\n', thisFolder)
% do work with path variable directing to each child folder.
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Behavior and Psychophysics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!