Read all text files in folder (nonsequential)

I need matlab to read all text files within a folder. The number typically are sequential; however, the limitation of the existing MATLAB script is that it doesn’t allow for non-consecutive numbered tests, beginning only at xxxx001.dat to be processed. I would like all .dat files contained within a specific folder to be processed at the same time.
RT_number=1917; t1start=tic; warning off MATLAB:xlswrite:AddSheet;
for i=1:999 tic; if i>=1 && i<=9
zero='00';
end
if i>=10 && i<=99
zero='0';
end
if i>=100 && i<=999
zero='';
end
filename=[int2str(RT_number) zero int2str(i) '.dat'];
end
fid=fopen(filename);

 Respuesta aceptada

Kelly Kearney
Kelly Kearney el 23 de Mayo de 2014
F = dir('*.dat');
for ii = 1:length(F)
fid = fopen(F(ii).name);
end
By the way, if they are sequential, a cleaner way to get the file names:
RT_number=1917;
for ii = 1:999
filename = sprintf('%d%02d.dat', RT_number, ii);
fid = fopen(filename);
end

2 comentarios

I suggest reading the help for dir. In this case, F(ii).name holds the same string as filename in your original example, i.e. the name of the file. You could add an extra line:
filename = F(ii).name;
but it's unnecessary (I'd only do that if you have a lot of code that already refers to the filename variable.)
Russell
Russell el 23 de Mayo de 2014
Can you please explain what you did? I have a very basic understanding of Matlab

Iniciar sesión para comentar.

Más respuestas (1)

Mahdi
Mahdi el 23 de Mayo de 2014
Based on what you said, if you have all the files in the same folder, you can open the folder in MATLAB and use dir to list all the folder contents (With other options if you want, or even tell dir which folder to list the contents for). Similarly, you can use ls.
You can then use a loop to open up these files, for example (assuming you're in the folder already)
filelist=ls;
[m, n] size(filelist);
for i=1:m
fid=fopen(filename(i,1:end))
end
You can do the same thing dir, but you would need to use filelist(i).name

1 comentario

Russell
Russell el 23 de Mayo de 2014
I need matlab to convert the data into an excel file. That is why I want it to open the files in the folder. It will be creating an excel sheet for each file.

Iniciar sesión para comentar.

Categorías

Más información sobre File Operations en Centro de ayuda y File Exchange.

Preguntada:

el 23 de Mayo de 2014

Comentada:

el 23 de Mayo de 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by