Loop through folders to pick data file

14 views (last 30 days)
Charles Sendegeya
Charles Sendegeya on 10 Nov 2021
Commented: Stephen23 on 11 Nov 2021
What is wrong with this code?
I want to access folders that each have a data file named specimen.dat, perform operations on it and then go back and pick a new data file (and so on..). The folders are in my root directory. But everytime I do so, the program picks only 1 specimen.dat file that is outside the folder I selected and performs rest of the script operations.
% Find all sample folders
Folders = uigetdir(matlabroot,'MATLAB Root Folder');
myFiles = dir(fullfile(Folders,'**/specimen.dat')); %gets all data files in folders
for myFile = 1:length(myFiles)
  1 Comment
Stephen23
Stephen23 on 11 Nov 2021
"The folders are in my root directory"
Do NOT save your own files under the installation folder of any application.

Sign in to comment.

Answers (1)

dpb
dpb on 10 Nov 2021
You shouldn't be putting your data files under the MATLABROOT tree....that's fraught with difficulties when upgrade.
MATLAB creates a working directory on installation; using it or a subdirectory under it or another entirely separate location for a given project would be far preferable.
We can't see the file structure you have created, however, nor do we know what the value of the variable Folders is so we have no way to diagnose what might have done.
What does myFiles contain when it returns after dir()?
If it does contain the desired files, then you've forgotten to show us the code that tries to open each in turn; it should look something like
for myFile=1:length(myFiles)
data=readmatrix(fullfile(myFiles(myFile).folder,myFiles(myFile).name));
% operate on data in data here...
end
The "veritable plethora" of like-looking variable names in the above is VERY difficult to parse; hence I would write the above more nearly like
d=dir(fullfile(Folders,'**/specimen.dat'));
for i=1:numel(d)
data=readmatrix(fullfile(d(i).folder,d(i).name));
% operate on data here...
end
where the temporary variables are much shorter and thus less clutter to wade through in reading the code. Your mileage may vary, but that's my strong preference after 40 years' coding...

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!