matlab - MATLAB 中的分组组合

标签 matlab matrix combinations

我是 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列的分组,一次取出2个矩阵A第2列所有可能的组合

特别是,我希望得到如下结果:

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

...      ...        ...

我知道我们可以使用函数combnk来获取所有组合,但我不知道如何在组中执行此操作。

最佳答案

使用 nchoosek (b = nchoosek(n,k) 返回二项式系数,定义为 n!/((n–k)! k!)。这是在 a 处取 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

关于matlab - MATLAB 中的分组组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496683/

相关文章:

c# - 如何获得子集的所有可能组合?

linux - Matlab 2011a 使用 64 位 Linux 上可用的所有内核?

matlab - 在 MATLAB 中为结构数组的字段赋值

arrays - MATLAB:遍历多个 double 组以查找最小/最大值

opencv - 在 Emgucv 或 Opencv 中将多个一维矩阵复制到一个大的一维矩阵中

ruby-on-rails - ruby w/permutations 中字符串中选定字符替换的所有可能排列或组合

string - 使用 dir 函数时出错 未为 'string' 输入定义

python - 如何在python中找到矩阵对角线上下元素的总和?

matlab - 如何在matlab中将每一行与另一个矩阵的每一行逐元素相乘?

r - 改进并加速代码以确定大量组合