2016-03-06 77 views
4

我總是被告知幾乎所有for循環都可以在MATLAB中省略,並且它們通常會減慢進程速度。那麼在這裏有辦法嗎?:在MATLAB中沒有for循環的多個數組的相交

我有一個單元陣列(tsCell)。 tsCell存儲具有不同長度的時間數組。我想找到的交叉時間陣列的所有時間陣列(InterSection):

InterSection = tsCell{1}.time 
for i = 2:length{tsCell}; 
    InterSection = intersect(InterSection,tsCell{i}.time); 
end 

回答

2

下面是使用uniqueaccumarray向量化方法中,假設有輸入單元陣列的每個單元內沒有重複 -

[~,~,idx] = unique([tsCell_time{:}],'stable') 
out = tsCell_time{1}(accumarray(idx,1) == length(tsCell_time)) 

採樣運行 -

>> tsCell_time = {[1 6 4 5],[4 7 1],[1 4 3],[4 3 1 7]}; 

>> InterSection = tsCell_time{1}; 
for i = 2:length(tsCell_time) 
    InterSection = intersect(InterSection,tsCell_time{i}); 
end 
>> InterSection 
InterSection = 
    1  4 

>> [~,~,idx] = unique([tsCell_time{:}],'stable'); 
out = tsCell_time{1}(accumarray(idx,1) == length(tsCell_time)); 
>> out 
out = 
    1  4 
+0

完美,很酷的解決方案! – Jonas

+0

@Jonas如果你碰到基準測試,你是否會友好地報告你可能在實際數據中獲得的運行時改進?我想知道這些數字。謝謝! – Divakar

+0

我運行一個包含三個不同時間數組的tsCell_time的小樣本(每個數組的入口長度約爲20000)。您的改進解決方案所用時間爲0.017398秒,而「原始」時間爲0.019724秒。 – Jonas

3

這裏的另一種方式。這也假定在每個原始矢量內沒有重複。

tsCell_time = {[1 6 4 5] [4 7 1] [1 4 3] [4 3 1 7]}; %// example data (from Divakar) 
t = [tsCell_time{:}]; %// concat into a single vector 
u = unique(t); %// get unique elements 
ind = sum(bsxfun(@eq, t(:), u), 1)==numel(tsCell_time); %// indices of unique elements 
    %// that appear maximum number of times 
result = u(ind); %// output those elements 
+0

我假設你的解決方案會更快,因爲你省略了累計 - 我會嘗試看看在某一時間點的流逝時間:) – Jonas

+1

@Jonas你也可以嘗試'histc(idx,1:max(idx)而不是'accumarray(idx,1)'。 – Divakar

+0

有趣的是,@Divakar解決方案要快得多(bsxfun解決方案需要一分鐘左右) - histc對於準確的解決方案同樣有效。 – Jonas

相關問題