views:

303

answers:

1

Hi,

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

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

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'

Ultimately, I then intended to use the for loop

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

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.

Thanks, S :-)

+3  A: 

Easy way, or the Easier way...


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'))

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.


A simpler alternative if you can rename your files is as follows:-

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

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

GoodLUCK!!
- CVS

CVS-2600Hertz