how to find subitems of a row in cell array matlab?

Deadly 提交于 2019-12-08 02:03:41

问题


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));


来源:https://stackoverflow.com/questions/44408921/how-to-find-subitems-of-a-row-in-cell-array-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!