Reading specific lines from multiple text files

3 views (last 30 days)
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

Accepted Answer

dpb
dpb on 1 Feb 2021
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 Comments
fadzhi
fadzhi on 2 Feb 2021
Many thanks for your comment but i am running it over a loop for multiple text file but i getting an error
D = 'c:files';
S = dir(fullfile(D, '*.txt'));
N = length(S);
h = cell(N,1);
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
dpb
dpb on 2 Feb 2021
Edited: dpb on 2 Feb 2021
...
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
>>

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Object Properties in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!