【问题标题】:Combination by groups in MATLAB在 MATLAB 中按组组合
【发布时间】:2014-12-16 02:43:35
【问题描述】:

我是 MATLAB 新手,目前卡在这个计算阶段。

我有一个矩阵如下:

A=
9      2835
9      3843
35     6532
35     6172
35     2034
35     2082
49     3273
49     3241
82     3694
82     2819
82     3334

我想根据矩阵A第1列中的组一次取出矩阵A第2列中的所有可能组合

我特别想得到如下结果:

9       2835        2843
35      2034        2082
35      6172        2082
35      6172        2034
35      6532        2082
35      6532        2034
35      6532        6172

...      ...        ...

我知道我们可以使用函数combnk 来获取所有组合,但我不知道如何分组。

【问题讨论】:

    标签: matlab matrix combinations


    【解决方案1】:

    使用 nchoosekb = nchoosek(n,k) 返回二项式系数,定义为 n!/((n–k)!k!)。这是一次取 k 项的 n 个项目的组合数。)可以引导您找到解决方案 -

    %// Find unique col-1 and ID them
    [unqA,~,id] = unique(A(:,1))
    
    %// Make groupings of A based on IDs
    grpA = arrayfun(@(n) A(id==n,:),1:max(id),'Uni',0)
    
    %// Form the pair-combinations within each groups
    combs = arrayfun(@(n) nchoosek(grpA{n}(:,2),2),1:numel(grpA),'Uni',0)
    
    %// Append the col-1 numbers with combinations for a cell array as output
    outc = arrayfun(@(n) [repmat(unqA(n),[ size(combs{n},1) 1 ]) combs{n}],...
                                                        1:numel(combs),'Uni',0)
    %// If you need a numeic array as the final output
    out = vertcat(outc{:})
    

    代码运行-

    >> A
    A =
               9        2835
               9        3843
              35        6532
              35        6172
              35        2034
              35        2082
              49        3273
              49        3241
              82        3694
              82        2819
              82        3334
    >> out
    out =
               9        2835        3843
              35        6532        6172
              35        6532        2034
              35        6532        2082
              35        6172        2034
              35        6172        2082
              35        2034        2082
              49        3273        3241
              82        3694        2819
              82        3694        3334
              82        2819        3334
    

    【讨论】:

    • 正要建议将nchoosek 放入循环中。 +1... 大约 19 小时后!我把当天的投票数用完了。
    • @rayryeng 谢谢!顺便说一句,你喜欢我的面膜吗!? ;)
    • 非常感谢。你救了我的命。它完美地工作。也许我问的很傻,但是你能帮我理解为什么arrayfun中使用'Uni',0吗?
    • @Anna 'Uni''UniformOutput' 和 AFAIK 的简写,下一个参数为零/假,告诉 MATLAB 将输出组合为单元格,因为在单元格中您可以保留不同的数组尺寸。作为一个例子,你可以看到,当我们使用arrayfun 来形成grpA 组时,每个组相对于其他组具有不同的大小。所以,UniformOutput 为假,我们让 MATLAB 将这些分组作为单元格。查看official doc 以获取有关UniformOutput 的更多信息。
    • @Divakar 非常好。适合你!最后也为你 +1
    猜你喜欢
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多