Run function on all subfolders and save as separate structs

I built a function that allows me to select a folder using uigetdir and process all the data files located in it. It takes a bunch of .txt files and saves the relevant data into a struct. The issue that I'm running into is that the function only targets one folder at a time; I usually have data saved in a main folder with several subfolders that are named according to the test variable being changed, and I don't want to have to manually run the function on all the subfolders.
For example: Main folder = testnumber1, inside the main folder are subfolders named pressure1, pressure2, etc (up to 20 folders)
What I'm looking to do is select the main folder (testnumber1) and have a recursive function call that allows me to get multiple structs labeled pressure1, pressure2, etc. I have the function set up already, but I don't know how to automate it and have it save the info to structs labeled with the folder names.

 Accepted Answer

You are looking for txt files? Then:
Mainfolder = 'D:\testnumber1\';
FileList = dir(fullfile(Mainfolder, '**', '*.txt')); % ** means recursively
Result = struct([]);
for iFile = 1:numel(FileList)
% FileList(iFile).folder is the specific subfolder
File = fullfile(FileList(iFile).folder, FileList(iFile).name);
... Process the File here
Result(iFile).File = File;
Result(iFile).Data = ???
end

3 Comments

This seems like it would work, but I think I'm looking for something a bit different. The function I built is used to select a folder and automatically process all the txt files in it, but I'm looking to select a main folder that has a bunch of subfolders and run the function on each subfolder specifically, not on the individual txt files. I think what I'm looking for is a way to list just the subfolders so that I can loop the function I have through the list.
Thanks for the help, I was able to use part of the code you sent me and adjusted it a bit so that I could specifically target the subfolders
mainfolder = uigetdir('D:\testnumber1\');
FileList = dir(fullfile(mainfolder, '**')); % ** means recursively
subfolders = unique({FileList.folder});
Result = struct([]);
for k = 2:numel(subfolders)
Result(k).data = myFunction(string(subfolders(k)));
end
Fine.
I prefer the simpler:
subfolders{k}
% instead of
string(subfolders(k))

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2018b

Asked:

on 7 Sep 2021

Commented:

Jan
on 8 Sep 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!