Loop function over multiple subfolders within one root folder?

Dear Matlab experts,
Hello, I am struggling from a very simple task (not for me, but probably for you..).
I have one root folder(workdir) and within the folder, there are 50 subject folders, and within each subject folders, there are 'DTI' folder > 'Date of the MRI scan' folder > 'subject ID' folder > then files that I want to copy to the destination folder.
Simply,
Root > A > DTI > Date > ID > *.files
B > DTI > Date > ID > *.files
C > DTI > Date > ID > *.files
. . . and so on to 50.
* Date folders and ID folders are all different in name under ABC.. folders.
I want to copy the files at the end of the subfolders to the another destination folder.
(+ I want to use movefile function to change file name with A,B,C folder names, but if it is too complicated, it is okay to move on)
Please Plase help me out..!!
Thank you in advnace!

답변 (1개)

Stephen23
Stephen23 2020년 1월 2일
편집: Stephen23 2020년 1월 2일
The MATLAB documentation shows you can either obtain the names (i.e. using dir) or generate them (e.g. using sprintf):
Something like this should get you started, make the required changes:
D = 'absolute or relative path to the Root directory';
Z = 'absolute or relative path to the destination directory';
S = dir(fullfile(D,'*')); % contents of the Root directory.
C = setdiff({S([S.isdir]).name},{'.','..'}); % keep directories only.
for k = 1:numel(C)
old = fullfile(D,'DTI','othersubfolders',C{k},'string that matches your filename/s');
new = Z;
copyfile(old,new)
end

댓글 수: 4

Thank you so much for the quick answer!
I think it would really useful and helpful, but one thing is that the subfolders name is different, because it is a different date of scanning time and the subject ID is also all different ..
Any suggestions ?
Thank you!!
"Any suggestions ?"
You will have to use dir, either:
  • detect the folder names and loop over them using nested loops, OR
  • use the recursive search syntax '**' (since R2016b), in which case you only need one loop.
What MATLAB version are you using?
I am currently using R2019a.
You can probably use dir's recursive search feature. something like this:
D = 'absolute or relative path to the Root directory';
Z = 'absolute or relative path to the destination directory';
S = dir(fullfile(D,'**','pattern that matches your filenames'));
for k = 1:numel(S)
old = fullfile(S(k).folder,S(k).name);
new = Z;
copyfile(old,new)
end

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 File Operations에 대해 자세히 알아보기

질문:

2020년 1월 2일

댓글:

2020년 1월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by