Check if cell array is a subset of a nother in Matlab

arrays, cell, matlab, subset

Solution

Given A and B

A={{'a','b'},{'c'},{'d','e'}}
B={{'a','b'},{'c','d'},{'e'}}

We can define a function `isSubset`, as follows:

isSubset = @(superSet,subSet)isempty(setdiff(subSet, superSet));

And test it:

isSubset(B{1}, A{1})  %true
isSubset(B{2}, A{2})  %true
isSubset(B{3}, A{3})  %false

Now we can use `isSubSet` and `cellfun` to define a function `isSubSetOfAny`, which checks to see if a particular subset is a subset of any of a set of sets, like this:

isSubSetOfAny = @(superSetSet, subSet) any(cellfun(@(x)isSubset(x, subSet), superSetSet));

And test it:

isSubSetOfAny(B, A{1})  %True
isSubSetOfAny(B, A{2})  %True
isSubSetOfAny(B, A{3})  %True

Now we can use `isSubSetOfAny` plus `cellfun` (again) to define `isEachMemberASubsetOfAny`, which performs the operation you describe:

    isEachMemberASubsetOfAny = @(superSetSet, subSetSet) all(cellfun(@(x)isSubSetOfAny(superSetSet, x), subSetSet));

And test it:

isEachMemberASubsetOfAny(B, A)    %Returns false

A_1 = {{'a','b'},{'c'},{'e'}};    %Define a variant of `A`
isEachMemberASubsetOfAny(B, A_1)  %Returns false

Problem

I have two cell arrays of strings as follows ``` A={{a,b},{c},{d,e}} B={{a,b},{c,d},{e}} ``` I want to check if A is a subset of B, meaning that each cell in A has a super-cell in B. In the given example it is not since A contains {d,e} while B does not have any cell that has those or more elements. I think ismember should be useful in this case, but I just could not write down the logic. Thank you!

Original source