MATLAB-从目录中读取文件? [英] MATLAB - read files from directory?

查看:182
本文介绍了MATLAB-从目录中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从目录中读取文件,并对每个文件进行迭代操作.此操作不需要更改文件.

I wish to read files from a directory and iteratively perform an operation on each file. This operation does not require altering the file.

我知道我应该为此使用for循环.到目前为止,我已经尝试过:

I understand that I should use a for loop for this. Thus far I have tried:

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

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

这里返回的错误向我(一个新手)暗示,使用ls()列出目录不会将内容分配给数据结构.

The error returned here suggests to me, a novice, that listing a directory with ls() does not assign the contents to a data structure.

其次,我尝试创建一个文件,该文件的每一行都包含一个文件路径,例如,

Secondly I tried creating a file containing on each line a path to a file, e.g.,

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

然后我使用以下代码读取该文件:

I then read this file using the following code:

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

此代码读取文件,但在路径中存在空格的地方创建换行符,即

This code reads the file but creates a newline where a space exists in the pathway, i.e.

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

最终,我打算使用for循环

Ultimately, I then intended to use the for loop

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

读取每个文件,但pdbread()引发错误,表明文件格式不正确或不存在.

to read each file but pdbread() throws an error proclaiming that the file is of incorrect format or does not exist.

这是由于读取路径文件时路径的换行符造成的吗?

Is this due to the newline separation of paths when the pathway file is read in?

非常感谢任何帮助或建议.

Any help or suggestions greatly apppreciated.

谢谢, S:-)

推荐答案

首先获取符合您条件的所有文件的列表:
(在这种情况下, C:\ My Documents \ MATLAB 中的 pdb 文件)

First Get a list of all files matching your criteria:
( in this case pdb files in C:\My Documents\MATLAB )

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

然后按如下所示读取文件:
(这里 i 可以从1到文件数不等)

Then read in a file as follows:
( Here i can vary from 1 to the number of files )

data = load(matfiles(i).name)

重复此操作,直到您读完所有文件为止.

Repeat this until you have read all your files.

如果可以重命名文件,则更简单的选择如下:-

首先保存需求.文件为1.pdb,2.pdb,3.pdb等...

First save the reqd. files as 1.pdb, 2.pdb, 3.pdb,... etc.

然后在Matlab中迭代读取它们的代码如下:

Then the code to read them iteratively in Matlab is as follows:

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

这篇关于MATLAB-从目录中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆