【问题标题】:How to find an matching element (either number or string) in a multi level cell?如何在多级单元格中找到匹配的元素(数字或字符串)?
【发布时间】:2021-04-06 11:43:21
【问题描述】:

我正在尝试在单元格数组的单元格中搜索匹配的数字(例如,2)或字符串('text')。单元格示例:

 A = {1 {2; 3};4 {5 'text' 7;8 9 10}};

There is similar question。但是,此解决方案仅在您想在单元格中查找数字值时才有效。对于数字和字符串,我也需要一个解决方案。 所需的输出应该是 1 或 0(值是否在单元格 A 中)以及找到匹配元素的单元格级别/深度。

【问题讨论】:

    标签: matlab cell-array


    【解决方案1】:

    对于您的示例输入,您可以通过将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,因为||&& 的“短路”行为。最后一个解决方案在如何将字符串与字符向量匹配方面仍然有点不一致,以防万一这对你很重要 - 看看你是否能弄清楚如何解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2020-02-23
      • 1970-01-01
      • 2020-04-04
      • 2016-05-23
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多