will_cheuk
will_cheuk

Reputation: 379

How to access a power set in matlab?

Given a dataset {1,2,...,50}, I want to write a for-loop such that in each loop, I can access a vector which may represent a subset of {1,2,...,50}. For example, in the first iteration, I may get a vector [1,0,...,0] and I know that it is equivalent to take an element 1 to form a subset. In the second iteration, I may get a vector [0,1,0,...,0] so that it is equivalent to take an element 2 to form a subset. I hope the for loop can run over all the subsets in the power set such that in each loop, it give a vector with entries either 0 or 1 so that I can know corresponding subset. Is it possible to do it?

Upvotes: 1

Views: 566

Answers (1)

Ash
Ash

Reputation: 4718

First of all, regarding the statement

I hope the for loop can run over all the subsets in the power set

I'm not sure if that is a good idea as even in the case that you give, i.e {1, 2, ..., 50}, there are 2^50 (note that this is greater than 1e15) subsets, and this is just a number of iterations that you can't carry on in a reasonable amount of time.

For smaller sets though (works fast enough for {1,...,18}), I think a possible approach would be to use a recursive solution similar to this:

function v=subsets(x)
    %%% x should be of size Mx1, with size(x,1)>0

    if ((size(x,1))==1)
        v={x,[]};

    else
        u=subsets(x(2:end,1));
        N=size(u,2);
        for i=1:N
            u{end+1}=[x(1,1) u{i}];
        end
        v=u;
    end

I've written it using cell arrays but I think that you wont have much difficulty using a similar solution with vectors of binary variables as in your description.

Upvotes: 2

Related Questions