Reputation: 379
I would like to consider power set in my code. I want to have in each loop, I obtain a subset of {1,2,3,...,n}
. For example, n=3
. In the first one loop, I would like to extract the number 1 and store in a variable Index
. Ultimately, I want to obtain Index=2
in the second loop, Index=3
in the third loop, Index=[1,2]
in the fourth loop, Index=[1,3]
in the fifth loop, Index=[2,3]
in the sixth loop and , Index=[1,2,3]
in the seventh loop. Of course I would like that n
can be any arbitrary number, say it can be 100. I can think of listing all the cases, but are there any ways to achieve my task?
Upvotes: 0
Views: 273
Reputation: 1426
nchoosk should find all k-long combinations. I suggest the following solution:
n = 3;
index = {};
for ii = 1:n
k = nchoosek(1:n,ii);
c = num2cell(k,2);
index(end+1:end+length(c),1) = c;
end
Another approach is to use a binary system where 001 means that you take only 1, 011 equals [1,2], 111 equals [1,2,3] etc. Then you can get it with dec2bin with no loop:
isChosen = dec2bin(1:2^n-1) == '1';
However, if we you must have it as a cell array you loop through the rows:
index1 = {};
for ii = 1:size(isChosen,1)
index1{ii,1} = find(isChosen(ii,:));
end
And then, if you insist on a sensible order:
[~,order] = sort(cellfun(@sum,index1));
index1 = index1(order);
Upvotes: 1