我刚开始使用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来获得所有的组合,但我不知道如何分组。
发布于 2014-12-16 04:05:21
使用nchoosek (b = nchoosek(n,k) )返回定义为n!/((n-k)的二项式系数!( k!)这是n项一次取k的组合数。)能帮你找到解决办法-
%// 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 3334https://stackoverflow.com/questions/27496683
复制相似问题