Extracting a number from an input (text file)?
1 回表示 (過去 30 日間)
古いコメントを表示
in the middle of my program, I need to read a Number from a file (text or DAT). This is a part of the file
##$SUBNAM9= <"">
##$SW= 2776.7173944802
##$SWIBOX= (0..15)
0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0
##$SW_h= 833333.333333333
##$SWfinal= 0
##$TD= 16384
##$TD0= 1
##$TE= 300
##$TE2= 300
I want Matlab to first read this file, then search for the number in front of "##$TD= ", which is 16384 in this example. Then
TD = 16384;
Thanks in advance
採用された回答
Walter Roberson
2011 年 5 月 27 日
T = regexp(TheString, '^##\$TD=\s*(.*) \s*$', 'tokens');
Then T{1} will be the string of the number. str2double(T{1}) if you want the numeric value.
8 件のコメント
Walter Roberson
2011 年 5 月 29 日
Darn default behaviours...
T = regexp(TheString, '(?-s)(?m)^##\$TD=\s*(\S+)\s*$', 'tokens');
The exact pattern to use depends on whether you have lines that have embedded spaces and on whether you need to trim the trailing spaces from such lines.
その他の回答 (1 件)
Laura Proctor
2011 年 5 月 27 日
I'll put my answer here since it's a little different, but Walter's response is definitely a lot more elegant.
fid = fopen('data.txt');
dataText = fgetl(fid);
while ~feof(fid)
if strfind(dataText,'##$TD')
ldata = textscan(dataText,'##$%s %f');
TD = ldata{2};
break
end
dataText = fgetl(fid);
end
fclose(fid);
2 件のコメント
Walter Roberson
2011 年 5 月 27 日
strfind() used in that way would find ##$TD anywhere in the string, but the following textscan() would only match if the line started with $$# . The difference could potentially be a problem -- e.g., if the user had happened to use a comment that included ##$TD as part of it.
strncmp(dataText,'##$TD',5) would be more robust than strfind() in this matter.
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!