2014-12-02 88 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