View License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
DIRWALK - Walk the directory tree

4.7 | 3 ratings Rate this file 8 Downloads (last 30 days) File Size: 4.1 KB File ID: #32036 Version: 1.1

DIRWALK - Walk the directory tree


Evgeny Pr (view profile)


03 Jul 2011 (Updated )

Generate the file names and dir names in a directory tree by walking the tree.

| Watch this File

File Information

Function generate the file names and directory names in a directory tree by walking the tree top-down. For each directory in the tree rooted at directory topPath. For each directory of tree you can call "Visitor Function" for files processing.

    [pathNames, dirNames, fileNames] = dirwalk(topPath)
    dirwalk(topPath, visitor)
    [visitorOutput1, visitorOutput2, ..., visitorOutputN] = dirwalk(topPath, visitor)
    [...] = dirwalk(topPath, visitor, visitorInput1, visitorInput2, ..., visitorInputN)

    topPath = fullfile(matlabroot, 'toolbox', 'matlab', 'demos');

    % Get files and dirs listing (default visitor)
    [pathNames, dirNames, fileNames] = dirwalk(topPath);
    % Call visitor function in each dir
    dirwalk(topPath, @(y,x) disp(strcat(y, filesep, {}')))

See help DIRWALK and TEST_DIRWALK for detailes examples.

MATLAB release MATLAB 7.9 (R2009b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (3)
12 Sep 2016 Pavel Komarov

%an auxilliary function to find all the leaf directories containing files
%of a given type
function paths = recursedir(pathsofar, type)
paths = [];
dirfiles = dir(pathsofar);
isdirs = [dirfiles(1:end).isdir];

ndx = find(isdirs);%the struct indicies of files that are subdirectories
for i = ndx(3:end)%1 is ., and 2 is .., so definitely skip to keep from going in circles
paths = [paths; recursedir([pathsofar '/' dirfiles(i).name], type)];

for i = find(~isdirs)%iterate over files that are not subdirectories
if (strfind(dirfiles(i).name, type))%if contains whatever file extension
paths = [paths; {pathsofar}];%cell array to keep strings separated
break;%don't keep adding the directory to the list

22 Jul 2014 Benjamin I

Benjamin I (view profile)

31 May 2012 Josiah McClurg

Functional, but I think it could be more concise and generic. Consider the following 12 lines:

function recurseDirectory(name, callback)
directory = dir(name);
for i = 1:length(directory)
if(~strcmp(directory(i).name,'.') && ~strcmp(directory(i).name,'..'))
recurseDirectory([name '/' directory(i).name], callback);
callback([name '/' directory(i).name]);

You can test the above code out with


if you like

10 Jul 2011 1.1

- Fixed bugs
- Added default visitor
- Deleted global variables
- Other improvements

Contact us