我有以下性能問題關於大的文本文件輸入(〜500K線)和後續的數據分析。刪除從文本文件reoccuring行與增強的性能
考慮具有與所述特徵模擬下面的示例性的結構,即兩個頭線可以在文本文件中某處再現文本文件data.txt
:
Name Date Val1 val2
--- ------- ---- ----
BA 2013-09-07 123.123 1232.22
BA 2013-09-08 435.65756 2314.34
BA 2013-09-09 234.2342 21342.342
我寫和其工作的代碼如下:
%# Read in file using textscan, read all values as string
inFile = fopen('data.txt','r');
DATA = textscan(inFile, '%s %s %s %s');
fclose(inFile);
%# Remove the header lines everywhere in DATA:
%# Search indices of the first entry in first cell, i.e. 'Name', and remove
%# all lines corresponding to those indices
[iHeader,~] = find(strcmp(DATA{1},DATA{1}(1)));
for i=1:length(DATA)
DATA{i}(iHeader)=[];
end
%# Repeat again, the first entry corresponds now to '---'
[iHeader,~] = find(strcmp(DATA{1},DATA{1}(1)));
for i=1:length(DATA)
DATA{i}(iHeader)=[];
end
%# Now convert the cells for column Val1 and Val2 in data.txt to doubles
%# since they have been read in as strings:
for i=3:4
[A] = cellfun(@str2double,DATA{i});
DATA{i} = A;
end
我選擇了在一切看在奧得河的字符串能夠去除在DATA
到處刪除標題行。
停止時間告訴我,代碼中最慢的部分是轉換[A] = cellfun(@str2double,DATA{i})
雖然str2double
已經是比較str2num
更快的選擇。第二個最慢的部分是textscan
。
現在的問題是,有沒有更快的方法來處理這個問題?
請讓我知道如果我應該進一步明確。如果有一個我從未見過的非常明顯的解決方案,請原諒我,現在我只用Matlab工作了三個星期。
這適用於我的數據。避免使用字符串進行雙倍轉換會使時間縮短約60%! – Lukas