Another Parsing Example

Consider the following data format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
!Agilent Technologies
!Agilent 
!Date: Thursday, November 23, 2006 05:48:58
!Correction: S11 S21 S12 S22 
!S2P File: Measurements: S11, S21, S12, S22:
# Hz S  dB   R 50
2820000000 -40 0 -40 -178.796 -40 -178.796 -40 0
2820225000 -40 0 -40 -177.592 -40 -177.592 -40 0
2820450000 -40 0 -40 -176.388 -40 -176.388 -40 0
2820675000 -40 0 -40 -175.1839 -40 -175.1839 -40 0
2820900000 -40 0 -40 -173.9799 -40 -173.9799 -40 0
2821125000 -40 0 -40 -172.7759 -40 -172.7759 -40 0
.
.
.
.
3179775000 -40 0 -40 -53.5786 -40 -53.5786 -40 0
3180000000 -40 0 -40 -52.3746 -40 -52.3746 -40 0
!End of file
!Agilent Exiting

You can use the following code to parse the data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function [parsedData]= importMyData(name)
%this function parses data files that have some header content
%and some ending content
 
%the input to this function is the file name of the data file.  
%If the data file is not in the current Matlab directory
%you must include the entire directory path.  
%opens the file    
fid = fopen(name);
 
%reads line one by one into a cell
a= 1;
line = 0;
while line ~= -1
    line = fgetl(fid);
    data{a} = line;
    a = a +1;
end
data(end) = []; %get rid of the last line
 
fclose(fid);
 
%this for loop determines where the numerical data starts
for p=1:length(data)
    if (~isempty(str2num(data{p}))) break; end
end
 
%this loop saves the numerical data into parsedData
%until the numerical data stops
for x=p:length(data)
    if(isempty(str2num(data{x}))) break; end
    temp = str2num(data{x});
    parsedData(x-p+1,:) = temp; 
 
end

End of tutorial.

Pages: 1 2 3