2011-02-01 237 views

回答

5

函数DIR实际上返回在给定的目录,每个文件或子目录一个structure array与一个结构元件。当getting data from a structure array,使用点符号访问字段将返回字段值的comma-separated list,每个结构元素具有一个值。这个以逗号分隔的列表可以是collected into a vector,方法是将它放在方括号[]cell array中,方法是将其放在花括号{}中。

我平时喜欢通过制作logical indexing使用,像这样得到目录中的文件或子目录名称的列表:

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 
2

不,你对dirnames.name返回的内容不正确。

D = dir; 

这是一个结构数组。如果你想要一个目录列表,这样做

isdirlist = find(vertcat(D.isdir)); 

或者我可以在这里使用cell2mat。请注意,如果您只是尝试D.name,则返回逗号分隔列表。你可以简单地将所有的名字作为单元格数组。

nameslist = {D.name}; 
0

假设“image_dir”是目录的名称,下面的代码演示如何确定哪些项目目录,哪些是文件,以及如何得到他们的名字。一旦你得到了那么多,建立一个只有目录或只有文件的清单才是直接的。

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 
相关问题