extracting values from text files as matrix format

1 次查看(过去 30 天)
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?

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2016-8-27
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,[]))'

更多回答(1 个)

dpb
dpb 2016-8-27
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...

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by