2

My question is how to use MATLAB to search for a certain type of files in a folder. I give an example to detail on my question:

Suppose we have the following folder as well as files in it:

My_folder
    Sub_folder1
        Sub_sub_folder1
              a.txt
        1.txt
        2.txt
    Sub_folder2
        3.txt
    abc.txt

In this example, I want to find all the .txt files in My_folder as well as its sub-folders. I was wondering what I could do with MATLAB. Thanks!

IKavanagh
  • 6,089
  • 11
  • 42
  • 47
feelfree
  • 11,175
  • 20
  • 96
  • 167
  • 4
    Not sure why this got so many down votes and closed, seems fairly reasonable, after-all the answer in python is fairly trivial (something like: `glob('*.txt')`) and the Matlab documentation can be a bit hard to follow (eg some things are not nesc where one would expect) – Frames Catherine White Jan 05 '15 at 23:57
  • `dir('**/*.txt')` in Matlab >R2016 – Brethlosze Jul 25 '18 at 13:30

3 Answers3

5

To my knowledge Matlab doesn't have an inbuilt function to do recursive directory searches, however there are a couple available for download on Matlab Central: here and here.

Alternatively you could write your own recursive function and use the dir function to search at each level for files matching your criterea or other directories to recurse into.

Alan
  • 3,307
  • 1
  • 19
  • 22
1

I agree with the Matlab Central options -- another method which I've used when MLC is not an option (no network, or customer computer, etc) is the quick and dirty dos commands:

dos(['dir /s/b ' mywildcard])  

The /s will do a recursive directory search for whatever wildcards you specify, and /b will make it so you only get filenames (complete will full path, but no headers, file sizes, etc).

This is obviously platform dependant, so is mostly used when you are forced to work without your "standard" set of utilities you've accumulated.

JonB
  • 350
  • 1
  • 7
  • If you want to use this approach and still require a modicum of cross platform capability you could write versions for both windows and unix, then switch between them based on the values of `getenv('os')` or `computer('arch')` calls. – Alan Apr 26 '13 at 11:01
0

Even though an answer has been accepted, I would like to point out Matlab's dir function.
This built-in function returns the contents of the folder in question. Furthermore, it indicates which content is a folder of its own. Therefore, with a little loop one could use this function to search sub-directories as well.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Schorsch
  • 7,761
  • 6
  • 39
  • 65
  • or check [this](http://stackoverflow.com/questions/2652630/how-to-get-all-files-under-a-specific-directory-in-matlab) response. – Schorsch Apr 26 '13 at 14:22