MATLAB Answers

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

1 view (last 30 days)
Luffy
Luffy on 29 Sep 2015
Commented: Luffy on 30 Sep 2015
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 ?

Accepted Answer

Cedric Wannaz
Cedric Wannaz on 29 Sep 2015
Edited: Cedric Wannaz on 29 Sep 2015
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 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!