2014-12-02 85 views
2

的。如果我有幾個數組:找到相交多陣列

A = [7 1 7 7 4]; 

B = [7 0 4 4 0]; 

C = [0 0 4 1 5]; 

D = [5 7 2 4 0]; 

我知道在Matlab「相交」可以找到兩個矩陣之間的共享內容與他們的索引。如果我想將它用於四個矩陣,我該怎麼做?

注:這可以用於兩個矩陣爲: [K,IA,IB] =相交(A,B)

http://uk.mathworks.com/help/matlab/ref/intersect.html

+0

也許這個回答可以幫助你:http://stackoverflow.com/questions/14080190 /發現 - 設置交集 - 多陣列 - 在matlab中 – 2014-12-02 20:19:01

+0

謝謝!我找到了這個我想要的方程。你的幫助真的很感激。 http://uk.mathworks.com/matlabcentral/fileexchange/24835-intersect-several-arrays – 2014-12-02 21:13:39

+0

不客氣。我發現@Divakar提供了一個非常好的和有效的答案;你可能想要檢查它並接受它,如果它幫助你。 – 2014-12-02 21:15:18

回答

2

你可以串聯所有輸入陣列(矢量)轉換成2D數組,然後嘗試查找所有輸入數組中存在的唯一元素。接下來介紹的bsxfun基於代碼試圖達到相同的 -

%// Concatenate all vector arrays into a 2D array 
M = cat(1,A,B,C,D) 

%// Find unique values for all elements in all arrays 
unqvals = unique(M(:),'stable')' %//' 

%// Find which unqiue elements are common across all arrays, which is the 
%// desired output 
out = unqvals(all(any(bsxfun(@eq,M,permute(unqvals,[1 3 2])),2),1)) 

代碼輸出 -

M = 
    7  1  7  7  4 
    7  0  4  4  0 
    0  0  4  1  5 
    5  7  2  4  0 
unqvals = 
    7  1  4  0  5  2 
out = 
    4 

爲了驗證針對intersect基於代碼,它的一種形式是這樣的 -

out1 = intersect(intersect(intersect(A,B,'stable'),C,'stable'),D,'stable') 

對於給定的輸入,它會給 -

out1 = 
    4 

爲了進一步驗證,假設你介紹一個7CC = [0 7 4 1 5],使得在所有輸入數組可用7,你將有輸出[7 4]


如果你想使bsxfun工作與2D陣列,可以更高效存儲,這裏是一個另類 -

%// Concatenate all vector arrays into a 2D array 
M = cat(1,A,B,C,D) 

%// Find unique values for all elements in all arrays 
unqvals = unique(M(:),'stable')' %//' 

[m1,m2] = size(M) %// Get size of concatenated 2D array 

%// Matches for all elements in all arrays against the unique elements 
matches = bsxfun(@eq,reshape(M',[],1),unqvals) %//' 

%// Desired output 
out = unqvals(all(any(permute(reshape(matches,m2,m1,[]),[1 3 2]),1),3)) 
+0

謝謝!我找到了這個我想要的方程。你的幫助真的很感激。 http://uk.mathworks.com/matlabcentral/fileexchange/24835-intersect-several-arrays – 2014-12-02 21:13:57

+0

我絕對需要更頻繁地開始使用bsxfun。來自我的+1! – 2014-12-02 21:21:42

+2

@ Benoit_11你使用IP很多,對吧?相信我,'bsxfun'與它一起創造奇蹟,特別是在MATLAB上的IP有很多範圍,因爲在很多情況下,你正在獨立處理像素!只要給它更多的練習,這就是所有:) – Divakar 2014-12-02 21:24:23