Searching for a variable in a text file & later taking its mean seperating out its units

조회 수: 1 (최근 30일)
I have a .txt file which is an output of a simulation software.I want to scan the txt file for a variable & collect that variable's value at each occurence & take its mean.
The text file is of the format:
%more text
*****************************************************************:
ID : 1010
A0 : 2.650000e+001
A1 : 2.650000e+001
time : 7.391000e+003 ns
mod : 0
sat : 0
angle : 0.000000e+000 radians
freq : 7.493000e+002 MHz
count : 0
*****************************************************************:
*****************************************************************:
ID : 1010
A0 : 2.850000e+001
A1 : 2.850000e+001
time : 8.391000e+003 ns
mod : 0
sat : 0
angle : 0.000000e+000 radians
freq : 7.493000e+002 MHz
count : 1
*****************************************************************:
*****************************************************************:
ID : 1010
A0 : 2.850000e+001
A1 : 2.850000e+001
time : 1.138600e+004 ns
mod : 0
sat : 0
angle : 0.000000e+000 radians
freq : 7.493000e+002 MHz
count : 2
*****************************************************************:
*****************************************************************:
%more text
So for the above text file if i have to search for say freq i should get [7.493e+2 7.493e+2 7.493e+2] whose mean is 7.493e+2 MHz.
My code as of now:
fid = fopen('ch0_TC_SYS_01.txt','r');
text = textscan(fid,'%s','Delimiter','');
text = text{1};
fid = fclose(fid);
idx = find(~cellfun('isempty',strfind(text,'freq : ')));
text(idx)
With the above code i get something like this:
'freq : 7.493000e+002 MHz'
'freq : 7.493000e+002 MHz'
'freq : 7.493000e+002 MHz'
.........
and after this i'm doing :
cellfun(@(x) x(8:20),abovecellarray,'un',0);
% & later
str2double;
But how can i do this dynamically seperating the units & all ?

채택된 답변

Cedric Wannaz
Cedric Wannaz 2015년 9월 29일
편집: Cedric Wannaz 님. 2015년 9월 29일
I would do something like:
content = fileread( 'ch0_TC_SYS_01.txt' ) ;
freqStr = regexp( content, '(?<=freq : )\S+', 'match' ) ;
freq = str2double( freqStr ) ;
if the unit is always Mhz, and
content = fileread( 'ch0_TC_SYS_01.txt' ) ;
freqUnit = regexp( content, 'freq : (\S+) (\S+)', 'tokens' ) ;
freqUnit = vertcat( freqUnit{:} ) ;
freq = str2double( freqUnit(:,1) ) ;
unit = freqUnit(:,2) ;
if you need the unit. Output of the second approach:
>> freq
freq =
749.3000
749.3000
749.3000
>> unit
unit =
'MHz'
'MHz'
'MHz'
  댓글 수: 2

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by