Looping Through Multiple Paths

조회 수: 3 (최근 30일)
Naomi Gaggi
Naomi Gaggi 2018년 10월 15일
답변: ag 2025년 4월 23일
I am trying to create a code that runs through multiple paths/different folders, within one large mother directory. The folders have the names Users 1, Users 2, Users 3, etc in the mother directory Group Analysis. I want to go 7 subfolders below Users 1, etc. I then want to create a for loop in which I execute commands in each of the subfolders consecutively. I have only successfully wrote a program for one path only:
s= {
{'/Users/Naomi/Desktop/GroupAnalysis/Users/jk/Documents/LongitudinalR01/Imaging/raw/c001/s1/0007_t1_mpr_AX_MPRAGE'},
s_out = {'/Users/Naomi/Desktop/output'};
for kk = 1:numel(s);
t = spm_select('FPList', (kk), '.*');
hdr = spm_dicom_headers(t);
spm_dicom_convert(hdr, 'all', 'flat', 'nii', char(s_out(kk)))
end
Thanks!!

답변 (1개)

ag
ag 2025년 4월 23일
Hi Naomi,
To process multiple directories within a "mother directory" and executing commands in each of the subfolders consecutively, you can use the MATLAB function "dir" to list all directories within and then execute the respective commands.
The below code snippet demonstrates how to achieve the same:
% Get a list of all user directories in the motherDir
userDirs = dir(fullfile(motherDir, 'Users*'));
% Loop over each user directory
for i = 1:length(userDirs)
if userDirs(i).isdir
userDirPath = fullfile(motherDir, userDirs(i).name);
% Navigate 7 subfolders deep
subDirPath = fullfile(userDirPath, 'jk/Documents/LongitudinalR01/Imaging/raw/c001/s1/0007_t1_mpr_AX_MPRAGE');
% Check if the subdirectory exists
if isfolder(subDirPath)
% Define the output directory
s_out = '/Users/Naomi/Desktop/output';
% Execute the respective command in the subdirectory, subDirPath
end
end
end
For more details, please refer to the following MathWorks documentations:
Hope this helps!

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by