Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 在2个数组中生成所有可能元素组合的有效方法_Algorithm_Matlab_Combinations_Permutation - Fatal编程技术网

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

Algorithm 在2个数组中生成所有可能元素组合的有效方法,algorithm,matlab,combinations,permutation,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] 这就是所有可能的组合(ab等于ba,因此只有1个组合应该在结果C数组上) matlab是否有一个内置函数可以用来实现这一点? 你能帮我吗?这里可以建议两种方法 方法#1 %// Form a concatenated array AB = [A(:) ; B(:)] %// Get pairwise multiplications between

我有一个数组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]
这就是所有可能的组合(ab等于ba,因此只有1个组合应该在结果C数组上)

matlab是否有一个内置函数可以用来实现这一点?
你能帮我吗?

这里可以建议两种方法

方法#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)

第二种方法基于,并且比第一种方法占用内存少。

请尝试以下代码:

%merge
AB = [A(:) ; B(:)]
%multiply to get all combinations
C=AB*AB'
%delete everything below the first diagonal
C=C(triu(true(numel(AB))));
另一种方法是(从统计工具箱)使用匿名函数:

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

使用两个向量并没有增加多少问题。您只需要每个
n的乘积选择2
串联的组合
x=[A(:);B(:)]


如果你有A=[2,4]B=[3,6]-12应该出现两次(3*4,6*2)还是只出现一次呢?两个数组是如何发挥作用的?在哪个数组中包含哪些元素似乎无关紧要。这应该与从
[A,B]
中选择2个元素相同。考虑得好!做了一些快速测试,这是真正大型阵列的最快测试@迪瓦卡谢谢!在最新版本的Matlab
pdist
中,使用mex文件进行实际计算;这一定是(部分)原因。我的测试表明,我的方法#1
bsxfun
执行得非常好,直到numel(A)是
2000
,即numel(AB)是
4000
,之后我猜
bsxfun
的大量内存需求开始出现,然后
pdist
开始发光。没有看到明显的赢家!
prod(x(nchoosek(1:numel(x), 2)), 2)