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

조회 수: 1 (최근 30일)
Lei Zeng
Lei Zeng 2021년 1월 24일
댓글: Lei Zeng 2021년 1월 24일
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!

답변 (1개)

KSSV
KSSV 2021년 1월 24일
편집: KSSV 2021년 1월 24일
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)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by