MATLAB: Dynamically change folders within a folder using MATLAB

change folders dynamicallychange sub-foldersmatlab script

Hi,
I would like to know whether I can change the folders dynamically within "streamflow_122" folder using MATLAB. I have over 150 sub-folders within "streamflow_122" folder. I have a MATLAB script to perform a task but I have change the folder by folder manually to run the script for each sub-folder.
Any ideas?
Thanks in advance.
cd ('C:\Users\Desktop\streamflow_122\')
myFolder = 'C:\Users\Desktop\streamflow_122\21601';

Best Answer

Damith - you can use the dir function to list the folder contents and iterate through over those that are directories/folders to perform the desired action. For example,
cd ('C:\Users\Desktop\streamflow_122\');
folderContents = dir;
for k=1:length(folderContents)
if folderContents(k).isdir
myFolder = fullfile(pwd, folderContents(k).name);
fprintf('%s\n',myFolder); % or perform task
end
end
You may need to add some additional logic to ensure that directories or folders such as '.' and '..' are ignored.