2012-03-17 45 views
1

基本上,我在一堆文本文件中有一堆重複的數據,如下所示(顯示兩部分):MATLAB:刪除4行標題,每14行重複一次,並在txt文件中保留第2 /第3列數據

t0 1/20/2012 05:41:05.068750 
delta t 0.100000 

time Y 
1/20/2012 05:41:05.068750 0.925883 
1/20/2012 05:41:05.168750 0.926540 
1/20/2012 05:41:05.268750 0.926540 
1/20/2012 05:41:05.368750 0.926540 
1/20/2012 05:41:05.468750 0.926869 
1/20/2012 05:41:05.568750 0.925225 
1/20/2012 05:41:05.668750 0.926540 
1/20/2012 05:41:05.768750 0.928185 
1/20/2012 05:41:05.868750 0.925554 
1/20/2012 05:41:05.968750 0.925225 
t0 1/20/2012 05:41:06.068750 
delta t 0.100000 

time Y 
1/20/2012 05:41:06.068750 0.926212 
1/20/2012 05:41:06.168750 0.924567 
1/20/2012 05:41:06.268750 0.926540 
1/20/2012 05:41:06.368750 0.925883 
1/20/2012 05:41:06.468750 0.914371 
1/20/2012 05:41:06.568750 0.907135 
1/20/2012 05:41:06.668750 0.906806 
1/20/2012 05:41:06.768750 0.903188 
1/20/2012 05:41:06.868750 0.902201 
1/20/2012 05:41:06.968750 0.906148 

我需要在MATLAB的方式只保留在第二和第三列10行數據(時間無日期和y的值),而這一切都存儲在一個變量,這樣我可以寫出來一個新的文本或xls文件。我甚至不需要時間值,因爲每個y值都以0.1秒爲增量。任何幫助將非常感激。

回答

1

批處理過程:

% Slurp in all lines. 
f = fopen('foo.txt'); 
c = textscan(f,'%s','Delimiter','\n'); 
lines = c{1}; 
fclose(f); 

% Remove headers. 
lines(1:14:end) = []; 
lines(1:13:end) = []; 
lines(1:12:end) = []; 
lines(1:11:end) = []; 

% Extract data. 
output = zeros(numel(lines),2); 
for i = 1:numel(lines) 
    x = lines{i}; 
    output(i,1) = datenum(x(1:19),'mm/dd/yyyy HH:MM:SS') + ... 
     str2double(x(20:26)); 
    output(i,2) = str2double(x(28:end)); 
end 

,或者作爲狀態機:

f = fopen('foo.txt'); 
output = []; 
while true 
    for i = 1:4 
     x = fgetl(f); 
     if x == -1 
      break 
     end 
    end 
    for i = 1:10 
     x = fgetl(f); 
     if x == -1 
      break 
     end 
     time = datenum(x(1:19),'mm/dd/yyyy HH:MM:SS') + ... 
      str2double(x(20:26)); 
     val = str2double(x(28:end)); 
     output(end+1,1:2) = [time,val]; 
    end 
    if x == -1 
     break 
    end 
end 
fclose(f); 
相關問題