Maddy
Maddy

Reputation: 2570

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

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

nameFolds = dir(pathFolder), 

I get . and .. + the subfolder names. I then have to run nameFolds(1) = [] twice. Is there a better way to get the subFolder names using Matlab? Thanks.

Upvotes: 34

Views: 73370

Answers (4)

Matthijs Noordzij
Matthijs Noordzij

Reputation: 1073

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

Upvotes: 0

Yas
Yas

Reputation: 5461

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

Upvotes: 2

theLtran
theLtran

Reputation: 81

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.

Upvotes: 8

yuk
yuk

Reputation: 19870

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.

Upvotes: 59

Related Questions