How can I get a list of all directory names and/or all files in a specific directory in MATLAB?
-
28-10-2019 - |
سؤال
There are two things I want to do:
- Get a list of all the directory names within a directory, and
- Get a list of all the file names within a directory
How can I do this in MATLAB?
Right now, I'm trying:
dirnames = dir(image_dir);
but that returns a list of objects, I think. size(dirnames)
returns the number of attributes, and dirnames.name
only returns the name of the first directory.
المحلول
The function DIR actually returns a structure array with one structure element per file or subdirectory in the given directory. When getting data from a structure array, accessing a field with dot notation will return a comma-separated list of field values with one value per structure element. This comma-separated list can be collected into a vector by placing it in square brackets []
or a cell array by placing it in curly braces {}
.
I usually like to get a list of file or subdirectory names in a directory by making use of logical indexing, like so:
dirInfo = dir(image_dir); %# Get structure of directory information
isDir = [dirInfo.isdir]; %# A logical index the length of the
%# structure array that is true for
%# structure elements that are
%# directories and false otherwise
dirNames = {dirInfo(isDir).name}; %# A cell array of directory names
fileNames = {dirInfo(~isDir).name}; %# A cell array of file names
نصائح أخرى
No. you are incorrect about what dirnames.name returns.
D = dir;
This is a structure array. If you want a list of which are directories, do this
isdirlist = find(vertcat(D.isdir));
Or I could have used cell2mat here. Note that if you just try D.name, is returns a comma separated list. You can get all of the names as a cell array simply though.
nameslist = {D.name};
Assuming that "image_dir" is the name of a directory, the following code shows you how to determine which items are directories and which are files and how to get their names. Once you've gotten that far, building a list of only directories or only files is straightforward.
dirnames = dir(image_dir);
for(i = 1:length(dirnames))
if(dirnames(i).isdir == true)
% It's a subdirectory
% The name of the subdirectory can be accessed as dirnames(i).name
% Note that both '.' and '..' are subdirectories of any directory and
% should be ignored
else
% It's a filename
% The filename is dirnames(i).name
end
end