How to read many arbitrary text files in MATLAB?

조회 수: 5 (최근 30일)
Phan
Phan 2014년 7월 24일
댓글: Phan 2014년 7월 25일
Dear everyone,
Please help me to solve this problem. I need to make a code that can read data from a text file for example ClCdCm.txt. If there is only one file, it can be read easily by the following code:
ClCd = fopen('ClCdCm.txt') % Read Cl, Cd and Cm data
C2_text = textscan(ClCd,'%s',4);
C2_data = textscan(ClCd, '%f %f %f %f');
However, now I have many text files for example ClCdCm1.txt , ClCdCm2.txt , ClCdCm3.txt ,... These files are generated by another program and we do not know how many file there will be. There can be one file, two files, ten files or whatever. But the files are named with a rule as above. Can anyone help me to write a code to manage and read these files?
Thank you so much!

채택된 답변

Kelly Kearney
Kelly Kearney 2014년 7월 24일
F = dir('ClCdCm*.txt');
nfile = length(F);
ctext = cell(nfile, 1);
cdata = cell(nfile, 1);
for ii = 1:length(F)
fid = fopen(F(ii).name);
ctext{ii} = textscan(fid,'%s',4);
cdata{ii} = textscan(fid, '%f %f %f %f');
fclose(fid);
end
I used cell arrays in this example because I wasn't sure if each file will have the same number of rows. You can modify that as appropriate to your data.
  댓글 수: 1
Phan
Phan 2014년 7월 25일
Thank you so much! What a great answer! Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sara
Sara 2014년 7월 24일
k = 1;
while exist(['ClCdCm',num2str(k),'.txt'],'file')
%insert code to read file
k = k + 1;
end

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by