2011-02-01 224 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 
相關問題