How to read multiple text files in a folder and create a cell array?
2 ビュー (過去 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!