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!