extracting values from text files as matrix format

1 回表示 (過去 30 日間)
sermet
sermet 2016 年 8 月 27 日
編集済み: sermet 2016 年 8 月 27 日
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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by