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

I have two arrays of row cells 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, which means that each cell in has a super-cell in B. In this example, this is not so, since A contains {d, e}, while B does not have a cell containing these or other elements. I think a member should be useful in this case, but I just couldn't write the logic.

Thank!

+5
source share
4 answers

Given A and B

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

We can define a function isSubsetas 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

isSubset cellfun isSubSetOfAny, , , :

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

:

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

isSubSetOfAny plus cellfun () isEachMemberASubsetOfAny, :

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

:

isEachMemberASubsetOfAny(B, A)    %Returns false

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

- :

function tf = is_subset(A,B)
    narginchk(2,2)
    assert(iscell(A) && all(cellfun(@iscellstr,A)));
    assert(iscell(B) && all(cellfun(@iscellstr,B)));

    for ia=1:numel(A)
        tf = false;
        for ib=1:numel(B)
            if all(ismember(A{ia},B{ib}));
                tf = true;
                break
            end
        end
        if ~tf
            break
        end
    end
end

[a,b,c,d,e] = deal('1','2','3','4','5');

A = {{a,b},{c},{d,e}};
B = {{a,b},{c,d},{e}};
is_subset(A,B)             %# false

B = {{a,b},{c,d,e},{e}};
is_subset(A,B)             %# true
+4

, a, b .. , :

A B , B, . :

 A={{'abc','b'},{'c'},{'d','e'}};
 B={{'aabc','b'},{'c','d'},{'d','e'}}; %Remove the first a to return true


 subset = true;
 for i = 1:length(A)
     found = false; 
     for j = 1:length(B)
         found = found || all(ismember(A{i},B{j}));
     end
     subset = subset && found;
 end
 subset
+2

a, b ..? , setdiff , . cellfun any all. :

all(cellfun(@(a)any(cellfun(@(b)isempty(setdiff(a,b)),B)),A))

If it is some other type, you can make a simple m file to check the super cell. Replace isempty(setdiff(a,b))with a call to this function. He will have to scroll through the elements aand check each of them to see if he exists in b.

+2
source

All Articles