我是 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/