使用MATLAB重复生成所有组合 [英] Generating all combinations with repetition using MATLAB
问题描述
如何创建所有带有重复的k-组合 k-multicombinations 或 multisubsets )的>?
How do I create all k-combinations with repetitions of a given set (also called k-multicombinations or multisubsets) using MATLAB?
这类似于笛卡尔乘积,但是应该仅将其排序不同的两行视为相同(例如,将向量[1,1,2]=~=[1,2,1]
视为相同),因此生成笛卡尔乘积,然后应用
This is similar to the cartesian product, but two rows that only differ by their sorting should be considered the same (e.g. the vectors [1,1,2]=~=[1,2,1]
are considered to be the same), so generating the cartesian product and then applying unique(sort(cartesianProduct,2),'rows')
should yield the same results.
示例:
调用nmultichoosek(1:n,k)
应生成以下矩阵:
Example:
The call nmultichoosek(1:n,k)
should generate the following matrix:
nmultichoosek(1:3,3)
ans =
1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 3 3
2 2 2
2 2 3
2 3 3
3 3 3
推荐答案
我们可以使用维基百科文章,它将没有重复类型n+k-1 choose k
的组合映射到大小为n
的k
-multicombinations.我们生成的组合没有重复,并使用bsxfun(@minus, nchoosek(1:n+k-1,k), 0:k-1);
映射它们.这将导致以下功能:
We can use the bijection mentioned in the wikipedia article, which maps combinations without repetition of type n+k-1 choose k
to k
-multicombinations of size n
. We generate the combinations without repetition and map them using bsxfun(@minus, nchoosek(1:n+k-1,k), 0:k-1);
. This results in the following function:
function combs = nmultichoosek(values, k)
%// Return number of multisubsets or actual multisubsets.
if numel(values)==1
n = values;
combs = nchoosek(n+k-1,k);
else
n = numel(values);
combs = bsxfun(@minus, nchoosek(1:n+k-1,k), 0:k-1);
combs = reshape(values(combs),[],k);
end
这篇关于使用MATLAB重复生成所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!