How to loop through a folder?

279 views (last 30 days)
andrew on 11 Mar 2014
Commented: Image Analyst on 10 Dec 2020
I currently have 24 folders within a folder and I was wondering if it was possible to loop through the 24 folders and extract information from a subfolder within the 24 folders.
  1 Comment
Brando Miranda
Brando Miranda on 30 Mar 2018
great question. This is some of the trivialest things to do in a language and its incomprehensible how hard it is to do in matlab.

Sign in to comment.

Answers (3)

Image Analyst
Image Analyst on 11 Mar 2014
See my attached demo where it recurses through a folder and all subfolders.
Image Analyst
Image Analyst on 10 Dec 2020
Yes, essentially it's
filePattern = sprintf('%s/**/*.*', topLevelFolder);
allFileInfo = dir(filePattern);
See my attached m-file for a full demo with tons of explanations.

Sign in to comment.

Sean de Wolski
Sean de Wolski on 11 Mar 2014
Edited: Sean de Wolski on 11 Mar 2014
You can use the dir command to give you the names and then loop over them.
files = dir;
directoryNames = {files([files.isdir]).name};
directoryNames = directoryNames(~ismember(directoryNames,{'.','..'}))
Now run the for-loop over directoryNames and apply your analysis to each
Stephen23 on 30 Mar 2018
Edited: Stephen23 on 30 Mar 2018
@Brando Miranda: "list comprehensions" exist only in Python. They do not exist in MATLAB.
The syntax in both your comments uses comma-separated lists. Comma-separated lists are very simple:

Sign in to comment.

manideep reddy
manideep reddy on 18 Apr 2018

see my code below but make sure that the folder which we are looping through contains only flolders and not files.

 cd pwd ; ## Or any other working directory you want
X = ls  ;
disp(X) ;
for itr = 1:size(X)(1)
	string_1 = X(itr,:) ;
	string_2{itr} = deblank(string_1) ;  ## This deletes the trailing blank spaces 			
for itr = 1:size(X)(1)
	cd ../
manideep reddy
manideep reddy on 20 Apr 2018
Thank you very much. I am actually not a computer science student. So, just answered the query without considering algorithm and complexity. Anyway, I will implement your suggestions/ recommendations in future. Thanks..!

Sign in to comment.


Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!