2010-06-10 167 views
13

我希望從目錄中讀取文件並對每個文件迭代執行操作。此操作不需要更改文件。MATLAB - 從目錄讀取文件?

我明白我應該爲此使用for循環。到目前爲止,我曾嘗試:

FILES = ls('path\to\folder'); 

for i = 1:size(FILES, 1); 
    STRU = pdbread(FILES{i}); 
end 

這裏返回的錯誤提示我,一個新手,即上市與LS一個目錄()不指定內容的數據結構。

其次我嘗試使用以下代碼創建包含在每一行的路徑的文件的文件,例如,

C:\Documents and Settings\My Documents\MATLAB\asd.pdb 
C:\Documents and Settings\My Documents\MATLAB\asd.pdb 

我然後讀取該文件:

fid = fopen('paths_to_files.txt'); 
FILES = textscan(fid, '%s'); 
FILES = FILES{1}; 
fclose(fid); 

此代碼讀取文件,但創建了一個換行符中存在空格的換行符,即

'C:\Documents' 
'and' 
'Setting\My' 
'Documents\MATLAB\asd.pdb' 

最終,我然後打算用for循環

for i = 1:size(FILES, 1) 
    PDB = pdbread(char(FILES{i})); 

讀取每個文件,但pdbread()引發錯誤宣告該文件是不正確格式的或不存在。

這是由於路徑文件讀入時路徑的換行分隔嗎?

任何幫助或建議大大apprecciated。

感謝, 小號:-)

回答

21

首先獲取的所有文件,符合條件的列表:
(在這種情況下PDB在Ç文件:\我的文檔\ MATLAB

matfiles = dir(fullfile('C:', 'My Documents', 'MATLAB', '*.pdb')) 

在一個文件中。然後如下:
(這裏i可以從1變化到數)

data = load(matfiles(i).name) 

重複此操作,直到您讀完所有文件。


一個簡單的替代,如果你能重命名文件如下: -

首先保存REQD。文件作爲1.pdb,2.pdb,3.pdb,...等

然後代碼反覆地閱讀他們在Matlab如下:

for i = 1:n 
    str = strcat('C:\My Documents\MATLAB', int2str(i),'.pdb'); 
    data = load(matfiles(i).name); 

% use our logic here 
% before proceeding to the next file 

end 
2

我複製這個從雅虎的答案!它對我很有用

% copy-paste the following into your command window or your function 

% first, you have to find the folder 
folder = uigetdir; % check the help for uigetdir to see how to specify a starting path, which makes your life easier 

% get the names of all files. dirListing is a struct array. 
dirListing = dir(folder); 

% loop through the files and open. Note that dir also lists the directories, so you have to check for them. 
for d = 1:length(dirListing) 
    if ~dirListing(1).isdir 
     fileName = fullfile(folder,dirListing(d).name); % use full path because the folder may not be the active path 

     % open your file here 
     fopen(fileName) 

     % do something 

    end % if-clause 
end % for-loop