How to read txt file contain unstructured array

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

Community Treasure Hunt

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

Start Hunting!

Translated by