所以我找到了一种方法来获取您的组合。你真的应该给出一个更简单的例子来解释你的问题(这就是我顺便解决的方法)。
程序是:
- 获取每组的所有
{2 element} 唯一组合。
- 然后为您获得的结果建立一个索引。通常每个子集都应该有一个索引,但由于它们的长度相同,因此唯一组合的数量将相同,因此您可以重复使用 4 倍相同的索引。
- 获取这4组索引的所有组合
- 最后,根据索引组合重建最终矩阵
代码如下:
%// prepare a few helper numbers
nSets = 4 ;
nElemPerSet = 2 ;
nCombs = nchoosek( numel(D1) ,nElemPerSet).^nSets ; %// <= nCombs=50625
%// for each set, get the unique combinations of 2 elements
s1 = nchoosek( D1 , nElemPerSet ) ;
s2 = nchoosek( D2 , nElemPerSet ) ;
s3 = nchoosek( D3 , nElemPerSet ) ;
s4 = nchoosek( D4 , nElemPerSet ) ;
%// now get the index of all the combinations of the above subsets
s = 1:size(s1,1) ;
combindex = all_combinations( repmat({s},1,4) ) ; %// <= size(combindex)=[50625 4]
%// now rebuild the full combinations based on above indices
combinations = zeros( nCombs , nSets*nElemPerSet ) ;
for ic = 1:nCombs
combinations(ic,:) = [s1(combindex(ic,1),:) s2(combindex(ic,2),:) s3(combindex(ic,3),:) s4(combindex(ic,4),:)] ;
end
可能有一种方法可以通过智能使用 arrayfun 来摆脱最后一个循环,但我将其作为练习留给读者。
此代码适用于您在问题中描述的 D1, D2, D3 and D4 的初始值,但如果您或任何人想逐步运行它以了解正在发生的事情,我强烈建议您尝试使用更简单的起始值。比如:
%// define 4 non-complex sets of 4 values each (all different)
nVal=4 ;
D1 = 1:nVal ;
D2 = D1(end)+1:D1(end)+nVal ;
D3 = D2(end)+1:D2(end)+nVal ;
D4 = D3(end)+1:D3(end)+nVal ;
注意函数all_combinations的使用。这只是我在重新打包在函数中的评论 (Generate a matrix containing all combinations of elements taken from n vectors) 中提到的答案。如果您经常处理组合问题,我建议您查看并添加书签(如果它对您有帮助,您也可以对其进行投票,这里就是这样做的)。
重新封装的功能是:
function combs = all_combinations( vectors )
%// function combs = all_combinations( vectors )
%//
%// example input :
%// vectors = { [1 2], [3 6 9], [10 20] }; %//cell array of vectors
%//
%// Credit: Luis Mendo : https://stackoverflow.com/questions/21895335/generate-a-matrix-containing-all-combinations-of-elements-taken-from-n-vectors
n = numel(vectors); %// number of vectors
combs = cell(1,n); %// pre-define to generate comma-separated list
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two
%// comma-separated lists is needed to produce the rows of the result matrix in
%// lexicographical order
combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
combs = reshape(combs,[],n); %// reshape to obtain desired matrix