在2个数组中生成所有可能的元素组合的有效方法

时间:2015-03-23 07:43:38

标签: algorithm matlab combinations permutation

我有一个数组A = [1,2]和B = [5,6]
我想生成一个数组C = [1 * 1,2 * 2,5 * 5,6 * 6,1 * 2,1 * 5,1 * 6,2 * 5,2 * 6,5 * 6] <登记/> 这就是所有可能的组合( b等于b a,因此只有1个应该在结果C数组上)。

matlab是否有内置功能可用于实现此目的?
你能救我吗?

4 个答案:

答案 0 :(得分:3)

这里可以提出两种bsxfun方法。

方法#1

%// Form a concatenated array
AB = [A(:) ; B(:)]

%// Get pairwise multiplications between all elements
allvals = bsxfun(@times,AB,AB.') %//'

%// Discard the repeated ones for the final output
C = allvals(bsxfun(@le,[1:numel(AB)]',1:numel(AB)))

方法#2

%// Form a concatenated array
AB = [A(:) ; B(:)]

%// Get "non-repeated" pairwise indices
[Y,X] = find(bsxfun(@le,[1:numel(AB)]',1:numel(AB))) %//'

%// Elementwise multiplications across all such pairs for final output
C = AB(X).*AB(Y)

第二个基于Fastest solution to list all pairs of n integers,并且比第一个方法的内存消耗更少。

答案 1 :(得分:2)

另一种方法是使用pdist(来自统计工具箱)和匿名函数:

AB = [A(:); B(:)];
C = [AB.'.^2 pdist(AB, @(x,y) x*y)];

答案 2 :(得分:1)

请尝试以下代码:

%merge
AB = [A(:) ; B(:)]
%multiply to get all combinations
C=AB*AB'
%delete everything below the first diagonal
C=C(triu(true(numel(AB))));

答案 3 :(得分:0)

对于使用两个向量的问题,它并没有多大帮助。您只需要串联n choose 2的每个x = [A(:); B(:)]组合的产品。

prod(x(nchoosek(1:numel(x), 2)), 2)
相关问题