【问题标题】:Efficient way to generate all possible combinations of elements in 2 arrays生成 2 个数组中所有可能的元素组合的有效方法
【发布时间】:2015-03-23 07:43:37
【问题描述】:

我有一个数组 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 是否有一个内置函数可以用来实现这一点?
你能帮帮我吗?

【问题讨论】:

  • 如果你有 A=[2,4] B=[3,6] - 12 应该出现两次 (3*4,6*2) 还是只出现一次?
  • 2 个数组 如何在这里发挥作用?似乎哪个元素在哪个数组中并不重要。它应该与从[A,B]中选择2个元素相同。

标签: algorithm matlab combinations permutation


【解决方案1】:

这里可以建议使用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,比第一种方法占用更少的内存。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这个想法不错!做了一些快速测试,这个对于非常大的阵列来说是最快的!
    • @Divakar 谢谢!在最新版本的 Matlab pdist 中,使用 mex 文件进行实际计算;这一定是(部分)原因
    • 好吧,我的测试表明我的方法 #1 bsxfun 表现非常好,直到 numel(A) 为 2000 即 numel(AB) 为 4000,之后我猜重bsxfun 的内存要求启动,然后 pdist 开始发光。没有看到明显的赢家!
    【解决方案3】:

    试试下面的代码:

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

    【讨论】:

      【解决方案4】:

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

      prod(x(nchoosek(1:numel(x), 2)), 2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-10
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多