Reading specific lines from multiple text files
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi all,
I am only interested in the numerical values of line 10 and line 11 of multiple text files. Right now, i am using below code, but with %s, i get complete string and with %f, i donot get any values. Will really appreciate some helop
clear;
D = 'T:\New\files';
S = dir(fullfile(D, '*.txt'));
N = length(S);
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r');
linenum = 10;
h(k)= textscan(fid,'%s',1,'delimiter','\n', 'headerlines',linenum-1);
fid=fclose(fid);
end
댓글 수: 0
채택된 답변
dpb
2021년 2월 1일
Ya' gotsa' skip the text to get to the floating point value...
...
T=cell2mat(textscan(fid,'%*s%f',1,'HeaderLines',linenum-1));
...
results in
>> T
T =
180
>>
댓글 수: 2
dpb
2021년 2월 2일
편집: dpb
2021년 2월 2일
...
h = zeros(N,1); % cell2mat() returns double, not cell
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r'); % open file
linenum = 12;
h(k) = cell2mat(textscan(fid, '%*s%f', 1, 'Headerlines', linenum-1));
fclose(fid);
end
Also, you changed value of linenum which won't match with the sample file location for the tmperature record.
NB: the above will only retrieve a number from a record with a single text string before the floating point number;
Messlaenge Extensometer: 50.000 [mm]
will fail.
> cell2mat(textscan(fid,'%*s%f %*[^\n]',inf,'Delimiter',':','HeaderLines',5))
ans =
50.0000
12.5000
1.5000
0.1000
180.0000
7.5000
NaN
72.2000
>> fid=fclose(fid);
>>
returns the array beginning with Messlaenge Extensometer: 50.000 [mm]
Or, can return the leading string as well...
>> frewind(fid)
>> (textscan(fid,'%s%f %*[^\n]',inf,'Delimiter',':','HeaderLines',5))
ans =
1×2 cell array
{8×1 cell} {8×1 double}
>> ans{:}
ans =
8×1 cell array
{'Messlaenge Extensometer' }
{'Probenbreite' }
{'Probendicke' }
{'Dehnrate' }
{'Temperatur' }
{'Pruefgeschwindigkeit' }
{'Kennwerte(*1)' }
{'Elastizitaetsmodul E (*2)'}
ans =
50.0000
12.5000
1.5000
0.1000
180.0000
7.5000
NaN
72.2000
>>
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!