对于您的示例输入,您可以通过将linked solution 中的ismember 替换为isequal 来匹配字符向量和数字。您可以通过跟踪函数必须围绕while 循环的次数来获取找到搜索值的深度。
function [isPresent, depth] = is_in_cell(cellArray, value)
depth = 1;
f = @(c) isequal(value, c);
cellIndex = cellfun(@iscell, cellArray);
isPresent = any(cellfun(f, cellArray(~cellIndex)));
while ~isPresent
depth = depth + 1;
cellArray = [cellArray{cellIndex}];
cellIndex = cellfun(@iscell, cellArray);
isPresent = any(cellfun(f, cellArray(~cellIndex)));
if ~any(cellIndex)
break
end
end
end
使用isequal 有效,因为f 仅对cellArray 本身不是元胞数组的元素调用。如果您希望能够搜索 NaN 值,请使用 isequaln。
请注意,这现在不会搜索 inside 数字、逻辑或字符串数组:
>> A = {1 {2; 3};4 {5 'text' 7;8 9 [10 11 12]}};
>> is_in_cell(A, 10)
ans =
logical
0
如果需要,可以将f 定义为
f = @(c) isequal(value, c) || isequal(class(value), class(c)) && ismember(value, c);
避免使用不兼容的数据类型调用ismember,因为|| 和&& 的“短路”行为。最后一个解决方案在如何将字符串与字符向量匹配方面仍然有点不一致,以防万一这对你很重要 - 看看你是否能弄清楚如何解决这个问题。