這裏是指一種方法性能 -
function out_idx = intersect_index(A,B)
s = max(max(A(:,1),[],1),max(B(:,1),[],1)) + 1;
A1D = A(:,2)*s + A(:,1);
B1D = B(:,2)*s + B(:,1);
BA1D = [B1D ; A1D];
[~,idx] = sort(BA1D);
out_idx = sort(idx(find(idx>numel(B1D))-1));
解釋這一點,我們可以在兩個元素的每一行轉換爲標考慮到每一個每行作爲索引元組,給我們1D
版本的輸入,A1D
和B1D
。然後我們將這些數據追加到一個數組中:BA1D = [B1D ; A1D]
並獲取排序後的索引。由於排序,來自A1D
的指數將具有較高的指數,表明這些是我們需要尋找的匹配。這是這裏的基本想法。
另外,還要注意是否有A
或B
負數,我們需要在min
帶來計算s
在開始。
時序和驗證
>> % --- Setup inputs
B = randi(100000,150000,2);
B = unique(B,'rows');
A = B(randperm(size(B,1),3072),:);
>> out1 = intersect_index(A,B); % Proposed in this post
>> out2 = find(ismember(B,A,'rows')); % @user2999345's soln
>> all(out1 == out2)
ans =
1
>> tic,find(ismember(B,A,'rows')); toc % @user2999345's soln
Elapsed time is 0.066226 seconds.
>> tic, intersect_index(A,B); toc % Proposed in this post
Elapsed time is 0.010360 seconds.