필터 지우기
필터 지우기

How to read txt file contain unstructured array

조회 수: 3 (최근 30일)
Biswanath Mahanty
Biswanath Mahanty 2015년 11월 27일
편집: Stephen23 2015년 11월 27일
I am having a text file e.g. res.txt that hold some output from an analysis looks like
----------------------
N count deleted R2
------------------------
1 3 1 4 5 0.91
2 5 6 2 6 8 9 0.82
3 2 11 7 0.65
How effectively I can read the data for further processing, e.g. B=importdata('res.txt'); A=B.data; make a rectangular matrix of data part, having some intermediate NaN entries and the data doesn't seems to have any arrangement. Any help be appreciated!

채택된 답변

Stephen23
Stephen23 2015년 11월 27일
편집: Stephen23 2015년 11월 27일
Try this:
fid = fopen('temp.txt','rt');
C = textscan(fid,'%[^\n]','HeaderLines',3);
fclose(fid);
rgx = '^(\d+)\s+(\d+)\s+((\s\d+)+)\s+(\d+(\.\d+))\s*$';
spl = regexp(C{1},rgx,'tokens','once');
spl = vertcat(spl{:});
out = cellfun(@(s)sscanf(s, '%f').', spl, 'UniformOutput',false)
This generates a cell array out, the third "column" contains vectors of values, the other columns are scalar numeric:
>> out =
[1] [3] [3x1 double] [0.9100]
[2] [5] [5x1 double] [0.8200]
[3] [2] [2x1 double] [0.6500]
>> out{1,3}
ans =
1 4 5
Because you did not provide us with a test file I had to create my own, which is available here:

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by