找到具有特定条件的可能组合

find possible combinations with specific condition

我想计算 1:16 与 10 个子集的所有可能组合。

combos = combntns(1:16,10)

但条件是返回的组合至少应具有以下向量的 1 个成员:

V1=1:4,V2=5:8,V3=9:12,V4=13:16,

有什么解决办法吗?

有了这个问题规模,您可以生成所有组合,然后 select 满足要求的组合:

n = 16;  %// number of elements to choose from
c = 10;  %// combination size
s = 4;   %// size of each group (size of V1, V2 etc)

combos = nchoosek(1:n, c); 
ind = all(any(any(bsxfun(@eq, combos, reshape(1:n, 1,1,s,[])),2),3),4);
combos = combos(ind,:);

这可以推广到通用元素任意条件向量,假设所有向量大小相同:

elements = 1:16;                    %// elements to choose from
c = 10;                             %// combination size
vectors = {1:4, 5:8, 9:12, 13:16};  %// cell array of vectors

s = numel(vectors{1});
combos = nchoosek(elements, c); 
ind = all(any(any(bsxfun(@eq, combos, reshape(cat(1,vectors{:}).', 1,1,s,[])),2),3),4); %'
combos = combos(ind,:);