How can I check whether an element is in a nested cell array?

让人想犯罪 __ 提交于 2019-12-14 02:43:55

问题


How can I check whether an element is in a nested cell array? ex:

A = {{4 5 6};{6 7 8}};
b = 5;

The function

ismember(b,A{1})

does not work. Is there any solution better than for-loop?


回答1:


Because each element is a cell, you don't have a choice but to use cellfun combined with ismember, which is the same as using a loop in any case. Your cells are specifically two-deep (per Andrew Janke). Each cell element in your cell array is another cell array of individual elements, so there is no vectorized solution that can help you out of this.

Assuming that each cell is just a 1-D cell array of individual elements, you would thus do:

A = {{4 5 6};{6 7 8}};
b = 5;
out = cellfun(@(x) ismember(b, cell2mat(x)), A);

Which gives us:

out =

     1
     0

This checks to see if the value b is in each of the nested cell arrays. If it is your intention to simply check for its existence over the entire nested cell array, use any on the output, and so:

out = any(cellfun(@(x) ismember(b, cell2mat(x)), A));

Because each cell element is a cell array of individual elements, I converted these to a numerical vector by cell2mat before invoking ismember.



来源:https://stackoverflow.com/questions/30036067/how-can-i-check-whether-an-element-is-in-a-nested-cell-array

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