如何检查元素是否在嵌套单元格数组中?

时间:2021-06-29 21:22:29

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?

不起作用。有没有比for-loop更好的解决方案?

1 个解决方案

#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.

因为每个元素都是一个单元格,所以你没有选择,只能使用与ismember结合的cellfun,这与在任何情况下使用循环都是一样的。你的细胞特别是两个深(每个Andrew Janke)。单元格数组中的每个单元格元素都是单个元素的另一个单元格数组,因此没有可以帮助您解决此问题的矢量化解决方案。

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:

这将检查值b是否在每个嵌套的单元格数组中。如果您打算在整个嵌套单元格数组中检查它是否存在,请在输出中使用any,所以:

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.

因为每个单元格元素都是单个元素的单元格数组,所以我在调用ismember之前通过cell2mat将它们转换为数字向量。

#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.

因为每个元素都是一个单元格,所以你没有选择,只能使用与ismember结合的cellfun,这与在任何情况下使用循环都是一样的。你的细胞特别是两个深(每个Andrew Janke)。单元格数组中的每个单元格元素都是单个元素的另一个单元格数组,因此没有可以帮助您解决此问题的矢量化解决方案。

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:

这将检查值b是否在每个嵌套的单元格数组中。如果您打算在整个嵌套单元格数组中检查它是否存在,请在输出中使用any,所以:

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.

因为每个单元格元素都是单个元素的单元格数组,所以我在调用ismember之前通过cell2mat将它们转换为数字向量。