MATLAB Answers

Run a script for all subfolders

10 views (last 30 days)
Hi
I have a script and I want to rut it for a folder. I should say that the folder has subfolders. The folder structure is like below:
'rocording\myproject\020320 (it is a date)\XYdata'
the first two folders are same but I have many folders for third subfolder (different dates) and one 'XYdata' folder inside each date folder.
I want to run my script for the text files inside the XYdata subfolders.

  0 Comments

Sign in to comment.

Accepted Answer

Benjamin Großmann
Benjamin Großmann on 9 Mar 2020
You can use the asterisk (*) as wildcard to generate a file pattern and the dir command to get a struct of all the matching files. Assuming we are in the directory where the rocording folder is located and your data are mat-files:
file_pattern = './rocording/myproject/*/xydata/*.mat';
data_dir = dir(file_pattern);
data_locations = fullfile({data_dir.folder}, {data_dir.name})
Then you can use fullfile to obtain a cell array of file locations. Now you can loop over this cell or use cellfun to do stuff with all the data.

  1 Comment

Adam Danz
Adam Danz on 9 Mar 2020
+1 good suggestion

Sign in to comment.

More Answers (1)

Adam Danz
Adam Danz on 9 Mar 2020
Try this out,
mainDir = 'C:\Users\name\Documents\MATLAB\rocording\myproject'; % <-- replace with your real path
% Get a list of content
content = dir(mainDir);
% Remove content that isn't a subdirectory
subDirs = {content.name}';
content(~[content.isdir]' | startsWith(subDirs, '.')) = [];
% Loop through each subdirectory
for i = 1:numel(content)
% Create full path to the XYdata directory
fullpath = fullfile(content(i).folder, content(i).name, 'XYdata');
% Test that it exists
assert(exist(fullpath,'dir')==7, ['Directory doesn''t exist: ', fullpath])
% Use fullpath for your script.
% To add filename, file = fullfile(fullpath, 'myFile.mat');
end

  5 Comments

Show 2 older comments
Adam Danz
Adam Danz on 9 Mar 2020
@Boby S, What is the value of fullpath when you get the error?
@Benni, I do like your suggestion to use wildcards, it's robust, but I think you're overestimating the difference in complexity from my answer.
Boby S
Boby S on 9 Mar 2020
....\Ha\XYdata
The 'HA' subfolder exists but I do not have 'XYdata' in this folder.
Adam Danz
Adam Danz on 9 Mar 2020
Ah, if the subfolder structure isn't consistent then the wildcard method is the way to go.

Sign in to comment.

Sign in to answer this question.


Translated by