【问题标题】:Finding and filtering elements in a MATLAB cell array在 MATLAB 元胞数组中查找和过滤元素
【发布时间】:2011-03-28 14:04:01
【问题描述】:

我有一个具有如下结构的元素列表(元胞数组):

mystruct = struct('x', 'foo', 'y', 'bar', 's', struct('text', 'Pickabo'));
mylist = {mystruct <more similar struct elements here>};

现在我想过滤 mylist 中所有 s.text == 'Pickaboo' 或其他预定义字符串的结构。在 MATLAB 中实现这一目标的最佳方法是什么?显然这对于​​数组来说很容易,但是对于单元格来说最好的方法是什么?

【问题讨论】:

    标签: list matlab filtering cell-array


    【解决方案1】:

    您可以为此使用CELLFUN

    hits = cellfun(@(x)strcmp(x.s.text,'Pickabo'),mylist);
    filteredList = mylist(hits);
    

    但是,为什么要制作一个结构单元?如果您的结构都具有相同的字段,则可以创建一个结构数组。要获得点击量,您可以使用ARRAYFUN

    【讨论】:

      【解决方案2】:

      使用cellfun

      mystruct = struct('x', 'foo', 'y', 'bar', 's', struct('text', 'Pickabo'));
      mystruct1 = struct('x', 'foo1', 'y', 'bar1', 's', struct('text', 'Pickabo'));
      mystruct2 = struct('x', 'foo2', 'y', 'bar2', 's', struct('text', 'Pickabo1'));
      
      mylist = {mystruct, mystruct1, mystruct2 };
      
      string_of_interest = 'Pickabo'; %# define your string of interest here
      mylist_index_of_interest = cellfun(@(x) strcmp(x.s.text,string_of_interest), mylist ); %# find the indices of the struct of interest
      mylist_of_interest = mylist( mylist_index_of_interest ); %# create a new list containing only the the structs of interest
      

      【讨论】:

        【解决方案3】:

        如果元胞数组中的所有结构都具有相同的字段('x''y''s'),那么您可以将 mylist 存储为结构体数组而不是元胞数组。你可以像这样转换mylist

        mylist = [mylist{:}];
        

        现在,如果您的所有字段's' 也包含具有相同字段的结构,您可以以相同的方式将它们全部收集在一起,然后使用STRCMP 检查您的字段'text'

        s = [mylist.s];
        isMatch = strcmp({s.text},'Pickabo');
        

        这里,isMatch 将是一个与 mylist 相同长度的logical index vector,其中找到匹配项,否则为零。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-01
          • 2014-07-10
          • 2019-07-18
          相关资源
          最近更新 更多