matlab:列出所有独特的子文件夹

时间:2013-11-29 11:10:54

标签: matlab recursion find directory

我想要一个包含所有完整子文件夹的列表。该列表不应包含任何父文件夹。

我使用

获取目录列表
dirs = regexp(genpath(basePath),['[^;]*'],'match');

然而,这些功能真的很慢。可能是因为我的文件夹包含数千个文件。

父文件夹的删除是这样完成的:是否有可能在代码大小和速度方面对其进行优化?

function [ ListOfDirs ] = findsubfolders( basePath )

dirs = regexp(genpath(basePath),['[^;]*'],'match');

index = 0;
for k = 1:numel(dirs)
    currFolder = dirs{k};
    if numel(strrep(currFolder, basePath,'')) ~= 0
        if isempty(strfind(currFolder, 'remove'))
            index = index + 1;
            selectedDirs{index} = currFolder;
        end
    end
end

dirs = selectedDirs;
idx = 0;
for k = 1:numel(dirs)
    currFolder = dirs{k};
    isNotParentFolder = false;
    for s = 1:numel(dirs)
        if s ~= k
            compFolder = dirs{s};
            if numel(strrep(strrep(currFolder, compFolder,''),currFolder,'')) ~= 0
                isNotParentFolder  = true;
            end
        end
        if isNotParentFolder
            idx = idx + 1;
            ListOfDirs{idx} = currFolder;
            break;
        end
    end
end

end

1 个答案:

答案 0 :(得分:2)

我建议您使用fileattribs来获取文件和文件夹名称。此函数以递归方式搜索给定基本文件夹中的所有文件和文件夹,然后您只能选择文件夹。如果您有许多文件或文件夹,它可能会很慢;但随后可能会采用任何其他方法:

[success,message,messageid] = fileattrib('c:\users\lmendo\Documents\*');
%// final '\*' is needed to make the search recursive
isfolder = [message(:).directory]; %// true for folders, false for files
[folders{1:sum(isfolder)}] = deal(message(isfolder).Name) %// keep folders only
%// folders is a cell array of strings with all folder names

要仅保留最深的文件夹,请使用strmatch。它检查字符串(表示文件夹)是否匹配另一个字符串的开头(然后是其子文件夹)。这比findsubfolders函数更简单(也许更快)。

isDeepest = cellfun(@(str) numel(strmatch(str,folders))==1, folders);
%// "==1" because each folder at least matches itself. So 1 match indicates
%// it's deepest, more matches indicates it's not.
deepestFolders = folders(isDeepest); %// keep deepest folders only
%// deepestFolders is a cell array of strings with all deepest-folder names