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 Center および File ExchangeData Import and Export についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by