MATLAB Answers

0

extracting values from text files as matrix format

Asked by sermet on 27 Aug 2016
Latest activity Edited by sermet on 27 Aug 2016
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?

  0 Comments

Sign in to comment.

2 Answers

Answer by Azzi Abdelmalek
on 27 Aug 2016
 Accepted Answer

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,[]))'

  0 Comments

Sign in to comment.


Answer by 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...

  0 Comments

Sign in to comment.