在MATLAB单元阵列中查找和过滤元素

时间:2010-08-11 19:30:00

标签: list matlab filtering cell-array

我有一个带有结构的元素列表(单元格数组),如下所示:

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

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

3 个答案:

答案 0 :(得分:12)

您可以使用CELLFUN

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

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

答案 1 :(得分:4)

如果您的单元格数组中的所有结构都具有相同的字段('x''y''s'),那么您可以将mylist存储为结构数组细胞阵列您可以像这样转换mylist

mylist = [mylist{:}];

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

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

此处,isMatch的{​​{3}}长度与mylist的长度相同,其中匹配项找到匹配,否则为零。

答案 2 :(得分: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