How to generate all collections of n subsets of 1:v?
2 views (last 30 days)
Show older comments
So for example, given n=3 and v=2, then I would want the function to generate:
{[1],[1],[1]}
{[1],[1],[2]}
{[1],[2],[2]}
{[2],[2],[2]}
{[1],[1],[1,2]}
{[1],[1,2],[2]}
{[1],[1,2],[1,2]}
{[1,2],[1,2],[1,2]}
{[1,2],[1,2],[2]}
{[1,2],[2],[2]}
As you can see I want to allow repetition in the n elements of each collection but no repetition within each subset (ie {[1],[1]} is allowed but {[1,1]} is not).
Many thanks in advance for any help.
4 Comments
Bruno Luong
on 31 Jul 2019
Edited: Bruno Luong
on 31 Jul 2019
For n=8 and v=8 you would have
>> (2^8-1)^8
ans =
1.7878e+19
possible combinations.
Steven Lord
on 31 Jul 2019
That's a lot of possible combinations. Probably not "more atoms than there are in the universe" but definitely "would take an infeasibly large amount of time to process each collection". At 1 combination per second:
>> years(seconds((2^8-1)^8))
ans =
566534541986.593
If you explain more about the problem you're trying to solve where you think you need to generate all these collections, we may be able to suggest a more efficient method of solving that problem without brute-forcing about 1.8e19 combinations.
Answers (2)
Bruno Luong
on 31 Jul 2019
v = 2;
n = 3;
B = 1:2^v-1;
c = repmat({B},1,n);
[c{:}] = ndgrid(c{:});
c = cat(n+1,c{:});
c = reshape(c,[],n);
B = arrayfun(@(b) find(dec2bin(b,v)-'0'), B, 'unif', 0);
R = B(c);
for k=1:size(R)
cellfun(@(a) fprintf('[%s] ', num2str(a)), R(k,:));
fprintf('\n');
end
Result is
[2] [2] [2]
[1] [2] [2]
[1 2] [2] [2]
[2] [1] [2]
[1] [1] [2]
[1 2] [1] [2]
[2] [1 2] [2]
[1] [1 2] [2]
[1 2] [1 2] [2]
[2] [2] [1]
[1] [2] [1]
[1 2] [2] [1]
[2] [1] [1]
[1] [1] [1]
[1 2] [1] [1]
[2] [1 2] [1]
[1] [1 2] [1]
[1 2] [1 2] [1]
[2] [2] [1 2]
[1] [2] [1 2]
[1 2] [2] [1 2]
[2] [1] [1 2]
[1] [1] [1 2]
[1 2] [1] [1 2]
[2] [1 2] [1 2]
[1] [1 2] [1 2]
[1 2] [1 2] [1 2]
0 Comments
Andrei Bobrov
on 31 Jul 2019
v = 2;
n = 3;
s = 1:v;
c = [];
for ii = 1:v
k = num2cell(nchoosek(s,ii),2);
c = [c, k(:)'];
end
idx = fullfact(ones(1,n)*numel(c));
out = c(idx);
0 Comments
See Also
Categories
Find more on Elementary Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!