list the subfolders in a folder - Matlab (only subfolders, not files)

后端 未结 4 1836
心在旅途
心在旅途 2020-12-25 12:13

I need to list the subfolders inside a folder using Matlab. If I use

nameFolds = dir(pathFolder), 

I get . and ..

相关标签:
4条回答
  • 2020-12-25 12:36

    The following code snippet just returns the name of sub-folders.

    % `rootDir` is given
    dirs = dir(rootDir);
    % remove `.` and `..`
    dirs(1:2) = [];
    % select just directories not files
    dirs = dirs([obj.dirs.isdir]);
    % select name of directories
    dirs = {dirs.name};
    
    0 讨论(0)
  • 2020-12-25 12:47

    This is much slicker and all one line:

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

    Explained: genpath() is a command which spits out all subfolders of the parentdir in a single line of text, separated by semicolons. The regular expression function regexp() searches for patterns in that string and returns the option: 'matches' to the pattern. In this case the pattern is any character not a semicolon = `[^;], repeated one or more times in a row = *. So this will search the string and group all the characters that are not semicolons into separate outputs - in this case all the subfolder directories.

    0 讨论(0)
  • 2020-12-25 12:48

    And to effectively reuse the first solution provided in different scenario's I made a function out of it:

    function [ dirList ] = get_directory_names( dir_name )
    
        %get_directory_names; this function outputs a cell with directory names (as
        %strings), given a certain dir name (string)
        %from: http://stackoverflow.com/questions/8748976/list-the-subfolders-
        %in-a-folder-matlab-only-subfolders-not-files
    
        dd = dir(dir_name);
        isub = [dd(:).isdir]; %# returns logical vector
        dirList = {dd(isub).name}';
        dirList(ismember(dirList,{'.','..'})) = [];
    
    end
    
    0 讨论(0)
  • 2020-12-25 12:51

    Use isdir field of dir output to separate subdirectories and files:

    d = dir(pathFolder);
    isub = [d(:).isdir]; %# returns logical vector
    nameFolds = {d(isub).name}';
    

    You can then remove . and ..

    nameFolds(ismember(nameFolds,{'.','..'})) = [];
    

    You shouldn't do nameFolds(1:2) = [], since dir output from root directory does not contain those dot-folders. At least on Windows.

    0 讨论(0)
提交回复
热议问题