I am looking for an efficient way to determine if a set is a subset of another set in Matlab or Mathematica.
Example: Set A = [1 2 3 4] Set B = [4 3] Set C = [3 4 1] Set
In Mathematica I propose using Alternatives for this.
For example, if we have a set {1, 2, 3, 4}
and we wish to test if set x
is a subset we could use: MatchQ[x, {(1|2|3|4) ..}]
. The advantage of this construct is that as soon as an element which does not belong is found the test will stop and return False.
We can package this method as follows:
maximal[sets_] :=
Module[{f},
f[x__] := (f[Union @ Alternatives @ x ..] = Sequence[]; {x});
f @@@ sets
]
maximal @ {{1, 2, 3, 4}, {4, 3}, {5, 1}, {3, 4, 1}, {4, 3, 2, 1}}
{{1, 2, 3, 4}, {5, 1}}