2015-08-16 52 views
1

我有一個包含大量數據格式的9列製表符分隔的.txt文件,但是有些條目在'type'內是空的。使用textscan容納.txt文件中的空白條目 - MATLAB

id id_2 s1  s2  st1  st2   type   desig num 
1 1 51371 51434 52858 52939 5:3_4:4_6:2_4:4_2:6 CO  1 
2 1 108814 108928 109735 110856 5:3_4:4_6:2_4:4_2:7 CO  2 
3 1 130975 131303 131303 132066 5:3_4:4_6:2_4:4_2:8 NCO 3 
4 1 191704 191755 194625 194803      NCO 4 
5 2 69355 69616 69901 70006      CO  5 
6 2 202580 202724 204536 205151 5:3_4:4_6:2_4:4  CO  6 

由於混合格式類型,我一直在使用textscan導入這樣的數據:

data = textscan(fid1, '%*f %f %f %f %f %f %*s %s %*[^\r\n]','HeaderLines',1); 

採取2-6列,跳過「type」,並採取了8列。

這種方法在具有空條目的行上失敗 - 它跳過了它,就好像它不是列,而是採用'NCO'或'CO'它將採用'4'或'5'。

有沒有辦法來防止這種情況?我知道我可以改變原始的.txt文件來爲空條目包含'NA'之類的東西,但這比讀取這些文件的更健壯的方式更不理想。

編輯

除了下面的答案,簡單地指定使用的分隔符出現來解決該問題:

data = textscan(fid1, '%*f %f %f %f %f %f %*s %s %*[^\r\n]','HeaderLines',1,'delimiter','\t'); 
+0

只會從「類型」列中丟失條目,或者是否會有其他列中的條目丟失? – Divakar

+0

只有'type'列。 – AnnaSchumann

回答

1

這裏有一個方法與importdatastrsplit -

%// Read in data with importdata 
data = importdata('data1.txt') %// 'data1.txt' is the input text file 

%// Split data 
split_data = cellfun(@(x) strsplit(x,' '),data,'Uni',0) 

N = numel(split_data) %// number of rows in input textfile 

%// Setup output cell and mask arrays 
out_cell = cell(9,N) 
mask = true(9,N) 

%// Set the "type" entry as zero in mask array for the rows in textfile 
%// that has corresponding entry missing 
mask(7,cellfun(@length,split_data)~=9)=0 

%// Use mask to set cells in out_cell from split data entries 
out_cell(mask) = [split_data{:}] 
out = out_cell' 

樣品運行 -

>> type data1.txt 

id id_2 s1  s2  st1  st2   type   desig num 
1 1 51371 51434 52858 52939 5:3_4:4_6:2_4:4_2:6 CO  1 
2 1 108814 108928 109735 110856 5:3_4:4_6:2_4:4_2:7 CO  2 
3 1 130975 131303 131303 132066 5:3_4:4_6:2_4:4_2:8 NCO 3 
4 1 191704 191755 194625 194803      NCO 4 
5 2 69355 69616 69901 70006      CO  5 
6 2 202580 202724 204536 205151 5:3_4:4_6:2_4:4  CO  6 
>> out 
out = 
    'id' 'id_2' 's1'  's2'  'st1'  'st2'  'type'     'desig' 'num' 
    '1'  '1'  '51371'  '51434'  '52858'  '52939'  '5:3_4:4_6:2_4:4_2:6' 'CO'  '1' 
    '2'  '1'  '108814' '108928' '109735' '110856' '5:3_4:4_6:2_4:4_2:7' 'CO'  '2' 
    '3'  '1'  '130975' '131303' '131303' '132066' '5:3_4:4_6:2_4:4_2:8' 'NCO'  '3' 
    '4'  '1'  '191704' '191755' '194625' '194803'      [] 'NCO'  '4' 
    '5'  '2'  '69355'  '69616'  '69901'  '70006'      [] 'CO'  '5' 
    '6'  '2'  '202580' '202724' '204536' '205151' '5:3_4:4_6:2_4:4'  'CO'  '6' 
+0

偉大的方法! +1 – AnnaSchumann