How to read multiple text files in a folder and create a cell array?
조회 수: 8 (최근 30일)
이전 댓글 표시
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
Sean de Wolski
2015년 3월 23일
@Stephen, Magic 8 ball says importfile is the default name given to functions generated with the import tool.
답변 (4개)
Stephen23
2015년 3월 23일
편집: Stephen23
2015년 3월 23일
>> 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
Sean de Wolski
2015년 3월 23일
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
2015년 3월 23일
If the files are all the exact same format, you might have some luck with datastore as well (new in r2014b).
doc datastore
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!