gpt4 book ai didi

matlab - 如何找到成对集合的所有组合

转载 作者:太空宇宙 更新时间:2023-11-03 20:35:39 25 4
gpt4 key购买 nike

我想生成 3 名男性和 2 名女性的成对组合的所有组合。有许多配对示例(例如 参见 this ),但没有一个涉及成对的集合。

例如,如果我有:

Men   = {'M1', 'M2'};
Women = {'W1', 'W2', 'W3'};

我想要的结果是以下几组:

(M1, W1), (M2, W2)
(M1, W1), (M2, W3)
(M1, W2), (M2, W1)
(M1, W2), (M2, W3)
(M1, W3), (M2, W1)
(M1, W3), (M2, W2)

谢谢。

最佳答案

其实很简单。要填充一组 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)

关于matlab - 如何找到成对集合的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com