如何在复杂的单元格中查找元素?
我有一个复杂的元胞数组,例如:
I have a complex cell array, ex:
A = {1 {2; 3};4 {5 6 7;8 9 10}};
如何在A中找到一个元素?例如,我想检查9是否在A中!
How can I find an element in A? For example, I want to check whether 9 is in A or not!!
如果单元格可以具有任意数量的嵌套级别,则只需递归所有它们以检查值.这是一个可以做到这一点的函数:
If you can have an arbitrary number of nesting levels for your cell arrays, you'll have to just recurse down all of them to check for the value. Here's a function that will do this:
function isPresent = is_in_cell(cellArray, value)
f = @(c) ismember(value, c);
cellIndex = cellfun(@iscell, cellArray);
isPresent = any(cellfun(f, cellArray(~cellIndex)));
while ~isPresent
cellArray = [cellArray{cellIndex}];
cellIndex = cellfun(@iscell, cellArray);
isPresent = any(cellfun(f, cellArray(~cellIndex)));
if ~any(cellIndex)
break
end
end
end
此函数将检查不是单元格数组的条目的值,然后提取作为单元格数组的条目以删除一个嵌套层.重复此过程,直到没有更多的单元格数组条目或找到该值为止.
This function will check the entries that aren't cell arrays for the value, then extract the entries that are cell arrays to remove one nesting layer. This is repeated until there are no more entries that are cell arrays, or the value is found.