how to find subitems of a row in cell array matlab

2019-05-27 11:14发布

问题:

I have cell array that is as follow:

S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];

and, i need to find rows of cell that are subitem of:

[10,20,30,40,50,60]

for above example result is :

1,2,5 

because row 1 and row 2 and and row 5 only have subitems of [10,20,30,40,50,60] .

in my work cell array is big. and i need a fast code.

回答1:

Let

S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];            % data
t = [10,20,30,40,50,60];   % target values

Then, you can apply ismember and all to each cell's contents via cellfun. The result is a logical vector, from which you obtain the desired indices with find:

result = find(cellfun(@(x) all(ismember(x, t)), S));

An alternative (I don't know which one will be faster in your case) is to replace ismember by computing all pairwise comparisons with bsxfun and then applying any:

result = find(cellfun(@(x) all(any(bsxfun(@eq, t(:), x(:).'), 1)), S));