How to read in data / specific data from an awkwardly formatted text file

1 view (last 30 days)
Hi everyone, although I'm not new to matlab, programming isnt really my MO, so any help would be greatly appreciated. I have a series of text files, and from each I need to read in just 4 numbers. The format of the file is pretty awkward though. I have copied and pasted the text file below, I dont know how to highlight text in the code so I have put a # in front of the data I need - the # is not in the original file
Inputfile :
particle03.crystal
50000 out of 50000 orientations
50000 good orientations
35497854 hits out of 50000000 incoming rays
Incoming energy : 35497854.0000000
Scattered energy : 35482099.1106260
Real abs. energy : 0.643676676686639
Missing energy : 15754.2456972814 = 4.438083974676729E-002 %
FreSnell-Error : 529.593800769572 = 1.491903709924471E-003 %
Finite tot. refl.: 2567.30819489775 = 7.232291267234780E-003 %
Finite ray recur.: 1535.72495842702 = 4.326247323083306E-003 %
Still missing : 11651.2125439567 = 3.282230115644921E-002 %
'scanning' cross section: 31.7229804213838
'polygon ' cross section: 32.0735320400461
extinction, scattering, absorption :
cross sec.: #64.1470634985082 #64.1470634985082
5.815840148590805E-007
effic.'s : 2.00000000000000 1.99999998186717
1.813283345697414E-008
w_0 : #0.999999990933583
g_rt : #0.396541133228651
g_diff (g_diff_discrete) : 0.994963507783535 2.317785388213539E-310
g_total: 0.695752323270166
delta forward peak : 1.072249481667976E-007
backward " : 6.998301309734189E-008
Any advice would be most helpful, thanks

Accepted Answer

Geoff Hayes
Geoff Hayes on 31 May 2014
Edited: Geoff Hayes on 31 May 2014
Hi Helen - since you are only interested in the three lines (of which there are four numbers) and if these lines are common to all of your files, you could just read each line in the file and match on the prefix for that line:
fid = fopen('particle03.crystal');
if fid>0
while ~feof(fid)
line = fgetl(fid);
if strfind(line,'cross sec.')
% do something
elseif strfind(line,'w_0')
% do something
elseif strfind(line,'g_rt')
% do something
% since found last number, break out
break;
end
end
end
The "do something" part of the code would be just to extract the numbers from the strings. Since the pattern in each is the same, you can look for the appearance of the colon and then convert everything after that to a number:
cidx = strfind(line,':');
numericData(1:2) = str2num(line(cidx+1:end))
where numericData is a 1x4 vector. Note that the above example is valid for the first condition where the line has two numbers; the other two assignments would be simpler. (Code assumes that there is no # prefix to each number.)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!