1

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?

I realize that this is extremely inefficient, but I am doing it for instructive purposes, not efficiency.

M.P. Korstanje
  • 8,279
  • 3
  • 33
  • 49
  • 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
  • Very hasty close. I would be very interested in seeing how any of these problems are equivalent. I'm not sure what kind of a thought process makes the n! permutations equivalent to the 2^n subsets of a set, or the cartesian product of two sets. – Christian Chapman Sep 10 '14 at 01:06
  • This is not a duplicate. Subsets (this problem) has no notion of order. With permutations (previous questions) the order matters – Clark Aug 26 '15 at 21:27
  • @bla It isn't a duplicate. See above. – Christian Chapman Mar 10 '20 at 18:18

1 Answers1

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

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