File Exchange

image thumbnail

SUBDIR *new*

version (616 Bytes) by Elmar Tarajan
Recursively search for files and/or directorys under given folder without using of global variables.


Updated 07 Dec 2004

No License

returns all subfolder under current path.
P = SUBDIR('directory_name')
stores all subfolders under given directory into a variable 'P'

[P F] = SUBDIR('directory_name')
stores all subfolders under given directory into a
variable 'P' and all filenames into a variable 'F'.
use sort([F{:}]) to get sorted list of all filenames.

Cite As

Elmar Tarajan (2021). SUBDIR *new* (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (18)

Vincent van Goor

Kouichi C. Nakamura

A vote for Gerrit Ecke's suggestion.
line 36 should be:
sub{end+1} = fullfile(CurrPath,i{:});

Kouichi C. Nakamura

Worked very well on Windows 10, thanks!!!!

Gerrit Ecke

Nice and simple, thank you. A suggestion to make it work both on Windows as well as on mac and Linux: replace line 36 from
sub{end+1} = [fullfile(CurrPath ’\' i{:})]; to
sub{end+1} = [fullfile(CurrPath,i{:})];

John Elam

This is a nice function. If you are using a Mac, change line 36 to '/' from '\' and it should start working.



John Peterson

Massimo-can you post your variation to MatlabCentral?

Massimo Cenciarini

I have modified the file shared and cleverly created by Elmar in the following way.

The modified version, has the option of an additional input argument which is a string. This string represents a pattern to restrict the search to those files with that pattern in their file name. Therefore, the list of subfolders is limited to those that contain files with the given pattern in their file name and also those files if needed. What I did not implemented is a search for subfolders with a name containing the pattern. If needed this can be implemented easily.

If interested, please let me know.

ChuanPeng Hu

Great!, better is one more argument could be used to select files based on name.


Great. This is what I was looking for. Quick and easy to use.


This doesn't work on Mac or Linux, because it assumes that '\' is the path separator. If line 36 is changed to

sub{end+1} = fullfile(CurrPath,i{:});

it should work on all platforms. You could also just replace '\' with pathsep, but fullfile is a little safer.


Thank you very much for the submission. It really helps me.


Swati Tiwari

Thank you so much!! This really helped me :)

Nikolay S.

Excellent, works nicely


great work!!!!

Durga Shrestha

nice work, save my time.

martin demel

The code is optimized and you can also get the name of the files. This is excellent working.

MATLAB Release Compatibility
Created with R13
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: RPCODE, folders sub-folders

Community Treasure Hunt

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

Start Hunting!