2

I want to run code for each (nonempty) 'sub-vector' of some vector v. For example:

v=1:3;             % [1,2,3]
Pv = subsets(v);   % { [1,2,3], [1,2], [1,3], [2,3], [1], [2], [3], [] }

for s in Pv
    % do things depending on each s in Pv;
end

But I do not know of any subsets(...) in matlab. How can this be done?


Note the collection of subsets of a vector is not the same as the collection of permutations.

Christian Chapman
  • 1,018
  • 10
  • 27
  • Idea: construct a matrix of dimension `2^length(v), length(v)`, and fill each row with every binary number up to that length, then use the rows as indexing. – Christian Chapman Sep 09 '14 at 23:58
  • another possible duplicate: http://stackoverflow.com/questions/4165859/matlab-generate-all-possible-combinations-of-the-elements-of-some-vectors#4169488 – bla Sep 10 '14 at 00:59
  • getting all permutations \neq iterating over all subsets... – Christian Chapman Sep 10 '14 at 01:01

1 Answers1

1
for ii=0:(2^length(v)-1)
    idx = logical( dec2bin( ii, length(v) )'-'0' );
    % do things to v(idx) 
end

Remember to check that v(idx) isn't empty.

Christian Chapman
  • 1,018
  • 10
  • 27