read the first 3 lines of a file and extract variables without reading the rest

1 visualización (últimos 30 días)
Hello,
I have a file "toread.txt" have following lines,
Profile=" time= 0.123456 "
VARIABLES = "X" "Y" "Z"
Z="XY" X= 10,Y= 10,
0.00000 0.00000 0.00000E+00
0.01953 0.00000 0.00000E+00
How could I read and extract the first three variables, t = 0.123456, X = 10, and Y = 10, without reading the rest of the document?
Thanks!

Respuestas (1)

KSSV
KSSV el 24 de En. de 2021
Editada: KSSV el 24 de En. de 2021
fid = fopen('file.txt');
tline = fgetl(fid);
val = cell(3,1) ;
n = 1 ;
val{n} = str2double(regexprep(tline, {'\D*([\d\.]+\d)[^\d]*', '[^\d\.]*'}, {'$1 ', ' '} ) ) ;
while ischar(tline)
disp(tline)
tline = fgetl(fid) ;
n = n+1 ;
val{n} = str2double(regexprep(tline, {'\D*([\d\.]+\d)[^\d]*', '[^\d\.]*'}, {'$1 ', ' '} ) ) ;
if n == 3
break
end
end
fclose(fid);
celldisp(val)

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by