其实很简单。要填充一组k对,您需要k男和k女,所以让我们首先找到k男和k女的所有可能组合:
%// Find all possible combinations of sets of k pairs of men and women
k = 2;
idx_m = nchoosek(1:numel(Men), k); % // Indices of men
idx_w = nchoosek(1:numel(Women), k); % // Indices of women
idx_w = reshape(idx_w(:, perms(1:k)), [], k); % // All permutations
然后让我们构造所有可能的k男人和k女人集合的组合:
[idx_comb_w, idx_comb_m] = find(ones(size(idx_w , 1), size(idx_m , 1)));
idx = sortrows([idx_m(idx_comb_m(:), :), idx_w(idx_comb_w(:), :)]);
idx = idx(:, reshape(1:size(idx, 2), k, [])'); %'// Rearrange in pairs
生成的矩阵idx
包含集合中男性和女性的索引(第一列为男性,第二列为女性,第三列为男性,第四列为女性,依此类推……)。
例子
Men = {'M1', 'M2'};
Women = {'W1', 'W2', 'W3'};
%// Find all possible combinations of sets of k pairs of men and women
k = 2;
idx_m = nchoosek(1:numel(Men), k);
idx_w = nchoosek(1:numel(Women), k);
idx_w = reshape(idx_w(:, perms(1:k)), [], k);
[idx_comb_w, idx_comb_m] = find(ones(size(idx_w , 1), size(idx_m , 1)));
%// Construct pairs from indices and print sets nicely
idx = sortrows([idx_m(idx_comb_m(:), :), idx_w(idx_comb_w(:), :)]);
idx = idx(:, reshape(1:size(idx, 2), k, [])');
%// Obtain actual sets
sets = cell(size(idx));
sets(:, 1:2:end) = Men(idx(:, 1:2:end));
sets(:, 2:2:end) = Women(idx(:, 2:2:end));
%// Print sets nicely
sets_t = sets';
fprintf([repmat('(%s, %s), ', 1, k - 1), '(%s, %s)\n'], sets_t{:})
这里生成的数组sets
已经适应了包含 和 的实际Men
值Women
。结果是:
(M1, W1), (M2, W2)
(M1, W1), (M2, W3)
(M1, W2), (M2, W1)
(M1, W2), (M2, W3)
(M1, W3), (M2, W1)
(M1, W3), (M2, W2)