Loop through folders to pick data file

6 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2021-11-11
"The folders are in my root directory"
Do NOT save your own files under the installation folder of any application.

请先登录,再进行评论。

回答(1 个)

dpb
dpb 2021-11-10
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...

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by