2010-06-10 171 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