extracting values from text files as matrix format

1 view (last 30 days)
I have a text file whose format as follows;
******** Week 887 almanac for PRN-01 ********
ID: 01
Health: 000
Eccentricity: 0.5846023560E-002
******** Week 887 almanac for PRN-02 ********
ID: 02
Health: 000
Eccentricity: 0.1588439941E-001
There are several ***** week ****** exist in the text file. I need to store each values (ID,Health, Eccentricity) as a matrix format. How can I store these values as a matrix or array format?

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 27 Aug 2016
fid=fopen('file.txt')
s=fgetl(fid)
out={}
while ischar(s)
out{end+1}=regexp(s,'(?<=(ID:|Health:| Eccentricity:))\s+\S+','match','once');
s=fgetl(fid);
end
fclose(fid)
idx=~cellfun(@isempty,out)
out=strtrim(reshape(out(idx),3,[]))'

More Answers (1)

dpb
dpb on 27 Aug 2016
I'll presume you'll also want to know the week number...
>> fid=fopen('semet.txt','r');
>> fmt1='%*s Week %f';
fmt2='ID: %f';
fmt3='Health: %f';
fmt4='Eccentricity: %f';
>> d=[]; % empty array for the data
>> while ~feof(fid) % until reach EOF
d=[d; ... % read and concatenate into array
cell2mat([textscan(fid,fmt1,'collectoutput',1) ...
textscan(fid,fmt2,'collectoutput',1) ...
textscan(fid,fmt3,'collectoutput',1) ...
textscan(fid,fmt4,'collectoutput',1)]).'];
end
>> d
d =
887.0000 1.0000 0 0.0058
888.0000 1.0000 0 0.0060
>> fid=fclose(fid);
>>
The in-place augmentation of the array isn't ideal from standpoint of efficiency but unless the file is quite large probably faster than the effort to scan the file and preallocate and it's certainly trivial to code...

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!