Matlab函数/脚本以递归方式列出所有子目录(仅文件夹)的路径

时间:2014-06-30 13:05:31

标签: matlab recursion directory

我需要递归列出目录中的所有文件夹。

e.g。在Z盘中,运行它应该产生这样的东西:

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\

另外,奖金问题,之后如何才能列出子文件夹?

e.g。

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

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

2 个答案:

答案 0 :(得分:5)

使用genpath功能。来自文档:

  

p = genpath(folderName)返回包含folderName的路径字符串   和folderName下面的多个子文件夹级别

答案 1 :(得分:4)

仅保留子项(最深层次)文件夹:在genpath中应用Dan's answer;转换为regexp的字符串单元格数组;并删除作为其他一些(strmatch检测前缀)的前缀的每个字符串:

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);