0

Hello I am trying to write a function in Matlab that takes a whole set and outputs all possible subsets of a given set.

For example: If I have a set

A = {1,2}

All possible subsets are

B = { {}, {1}, {2}, {1,2} }

I have tried nchoosek

Any ideas? Kinda lost on how I should implement this?

  • Why do you need all possible sets? Obtaining all those is either trivial or impossible. Trivial in case of a few elements, like you have, impossible for more than (roughly) 12 elements, given it grows factorially. You cannot possibly process all of those, let alone store in your RAM. – Adriaan Dec 01 '22 at 14:04

1 Answers1

-3

Given set S with n elements, there are 2^n subsets, including the empty set {}. The function nchoosek is the appropriate way to perform this operation. You can try the script below. It does not display the empty set.

set = [1,2,3,4,5]

for i=1:length(set):
    disp(nchosek(set, i))
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Bruno Peixoto
  • 211
  • 1
  • 4
  • 17
  • 1
    OP already mentions `nchoosek`. Plus, as I said in my comment and you mention here: this will create a ridiculously large number of sets very quickly, thus it's infeasible for all but the trivially small sets. – Adriaan Dec 01 '22 at 14:20
  • It is computationally possible, although your judgment ridicules the effort. I find it very unpleasing. – Bruno Peixoto Dec 01 '22 at 14:21
  • It's computationally possible for `n` very small (the docs suggest up to `n=10`). As soon as `n=30` you'll need more computational power than available in the biggest clusters. – Adriaan Dec 01 '22 at 14:22
  • Great. It seems a great application for generators of low cardinality. – Bruno Peixoto Dec 01 '22 at 14:23