找到多个数组的交集

时间:2014-12-02 20:10:21

标签: arrays matlab matrix

如果我有几个数组:

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

1 个答案:

答案 0 :(得分: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

要进一步验证,请假设您在7中引入C,即C = [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))
相关问题