【问题标题】:matlab: list all unique subfoldersmatlab:列出所有唯一的子文件夹
【发布时间】:2013-11-29 11:10:53
【问题描述】:

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

我使用

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

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

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

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

【问题讨论】:

标签: matlab recursion find directory


【解决方案1】:

我建议您使用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

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 2018-08-06
    • 2011-05-11
    • 1970-01-01
    • 2021-08-12
    • 2016-02-26
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多