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

1 view (last 30 days)
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!

Answers (1)

KSSV
KSSV on 24 Jan 2021
Edited: KSSV on 24 Jan 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)

Categories

Find more on Data Import and Export 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!