如何检查元素是否在嵌套单元格数组中? [英] How can I check whether an element is in a nested cell array?

查看:131
本文介绍了如何检查元素是否在嵌套单元格数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

函数

ismember(b,A{1})

不起作用. 有没有比for循环更好的解决方案?

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

推荐答案

由于每个元素都是一个单元格,您别无选择,只能使用

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

哪个给了我们

out =

     1
     0

这将检查值b是否在每个嵌套单元格数组中.如果您只是想检查整个嵌套单元格数组中是否存在它,请在输出中使用any,如此:

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

由于每个单元格元素都是单个元素的单元格数组,因此我通过 cell2mat ,然后再调用ismember.

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

这篇关于如何检查元素是否在嵌套单元格数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆