【问题标题】:How to fill a cell array of strings with the indices of its cells in another array of strings?如何用另一个字符串数组中的单元格的索引填充一个字符串单元格数组?
【发布时间】:2017-01-11 15:14:42
【问题描述】:

如果找到单元格内容(字符串),我正在尝试用另一个字符串单元格数组data(269x1)中每个单元格的索引填充字符串单元格数组attributes(764x1 单元格)在data。为此,我编写了以下代码:

for i=1:length(attributes)
    for j=1:length(data)
        attributes{i,1}=strfind(data{j,1}, attributes{i,1});
    end
end

我得到了空单元格:

【问题讨论】:

    标签: string matlab cell-array indices


    【解决方案1】:

    您在内部循环的第一次迭代中覆盖 attributes

    例子:

    data{1} = 'aabbcc';
    data{2} = 'bbaacc';
    data{3} = 'ccaabb';
    
    attributes{1} = 'aa';
    attributes{2} = 'bb';
    attributes{3} = 'cc';
    
    for i = 1:length(attributes)
        for j = 1:length(data)
            attributes{i} = strfind(data{j}, attributes{i});
        end
    end
    

    内部循环第一次迭代后j = 1:
    attributes{1} = 1

    内部循环第一次迭代后j = 2:
    attributes{1} = []

    因为 attributes{1} = 1 来自上一次迭代。
    attributes{i} = strfind(data{j}, attributes{i}); 相当于:
    attributes{1} = strfind(data{2}, 1);
    并且在数据中找不到 1{2}。

    您可能的意思是,类似于以下代码:

    data{1} = 'aabbcc';
    data{2} = 'bbaacc';
    data{3} = 'ccaabb';
    
    attributes{1} = 'aa';
    attributes{2} = 'bb';
    attributes{3} = 'cc';
    
    %Initialize new 2D cell array.
    attrib_indexes = cell(length(attributes), length(data));
    
    for i = 1:length(attributes)
        for j = 1:length(data)
            %Store result in attrib_indexes{i, j} instead of attributes.
            attrib_indexes{i, j} = strfind(data{j}, attributes{i});
        end
    end
    

    我建议你学习使用调试器,它比在 Stack Overflow 中发布问题更容易......

    【讨论】:

      【解决方案2】:

      您可以使用one of the variants of strfind 一次查看所有data

      att_ind = cell(length(attributes),length(data)); % Initialize a result cell array
      for k = 1:length(attributes)
          att_ind(k,:) = strfind(data, attributes{k});
      end
      

      这将产生一个length(attributes)-by-length(data) 元胞数组,这样 att_ind(k,n)attributes{k}data{n} 中的所有实例。如果没有此类实例,则 att_ind(k,n) 为空单元格。

      【讨论】:

        猜你喜欢
        • 2013-07-22
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-18
        • 2015-10-18
        相关资源
        最近更新 更多