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?
댓글 수: 0
채택된 답변
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,[]))'
댓글 수: 0
추가 답변 (1개)
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...
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!