Borrar filtros
Borrar filtros

Reading specific lines from multiple text files

4 visualizaciones (últimos 30 días)
fadzhi
fadzhi el 1 de Feb. de 2021
Editada: dpb el 2 de Feb. de 2021
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

Respuesta aceptada

dpb
dpb el 1 de Feb. de 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 comentarios
fadzhi
fadzhi el 2 de Feb. de 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 el 2 de Feb. de 2021
Editada: dpb el 2 de Feb. de 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
>>

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by