How to read multiple text files in a folder and create a cell array?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi, i have a folder with 432 text files named 00001.txt, 000002.txt...etc. I will like to create a matrix or a cell array with the information of these files. I used the import tool with the first file for creating a function like this:
function Untitled1 = importfile1(filename, startRow, endRow) %IMPORTFILE Import numeric data from a text file as a matrix.
Then i used a for loop for importing data from each text file into the cell array:
numFiles = 432; startRow = 2; endRow = inf; myData = cell(1,numFiles);
for fileNum = 1:numFiles fileName = sprintf('00000%02d.txt',fileNum); myData{fileNum} = importfile(fileName,startRow,endRow); end
But it shows the following message:
Error using textscan Invalid file identifier. Use fopen to generate a valid file identifier.
Error in importfile (line 37) dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
I will appreciate any help, thanks
2 comentarios
Sean de Wolski
el 23 de Mzo. de 2015
@Stephen, Magic 8 ball says importfile is the default name given to functions generated with the import tool.
Respuestas (4)
Stephen23
el 23 de Mzo. de 2015
Editada: Stephen23
el 23 de Mzo. de 2015
>> S = dir('*.txt');
>> N = {S.name};
where N is a cell array of all of the files that match the given filename string. Then you don't need to worry about generating the filenames yourself.
You might also like to compare the other file-reading functions, such as csvread, dlmread and textscan. These might be simpler to use in your loop, and a little faster too. You might also like to read MATLAB's own advice on importing a sequence of files:
and the two examples given here:
0 comentarios
Sean de Wolski
el 23 de Mzo. de 2015
Instead of sprintf, use num2str to build a string that always has the same length
num2str(ii,'%05i')
(or 6i, your example is inconsistent)
compare:
>> num2str(2,'%05i')
ans =
00002
>> num2str(243,'%05i')
ans =
00243
Sean de Wolski
el 23 de Mzo. de 2015
If the files are all the exact same format, you might have some luck with datastore as well (new in r2014b).
doc datastore
0 comentarios
Ver también
Categorías
Más información sobre Text Files en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!