AMcNall
AMcNall

Reputation: 529

Matlab function/script to list the paths of all subdirectories (folders only) recursively

I need to recursively list all folders in a directory.

e.g. In Z drive, running it should produce something like this:

Z:\

Z:\Home\

Z:\Home\A Folder\

Z:\Home\A Folder\testing\

Z:\Home\B Folder\

Z:\Home\C Folder\

Z:\Home\C Folder\test2\

Z:\Test 3\

Also, bonus question, afterward how can I only list the children folders?

e.g.

Z:\Home\A Folder\ < This would be removed

Z:\Home\A Folder\testing\  <This would be kept

Upvotes: 1

Views: 638

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

To only keep the children (deepest-level) folders: apply genpath as in Dan's answer; convert to a cell array of strings with regexp; and remove each string that is a prefix of some other (strmatch detects prefixes):

p = genpath('C:\Users\lmendo\Documents'); %// argument is base folder
folders = regexp(p,';','split'); %// split into strings
folders = folders(1:end-1); %// remove last element (it's empty)
valid = false(size(folders));
for n = 1:numel(folders)
    valid(n) = numel(strmatch(folders(n),folders))==1; %// 1 means the folder is 
    %// only a prefix of itself
end
children_folders = folders(valid);

Upvotes: 4

Dan
Dan

Reputation: 45741

Use the genpath function for this. From the docs:

p = genpath(folderName) returns a path string that includes folderName and multiple levels of subfolders below folderName

Upvotes: 5

Related Questions