在MATLAB的单元数组中查找和筛选元素

9

我有一个元素列表(单元数组),其中包含像这样的结构体:

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

现在,我想筛选mylist中的所有结构体,其中s.text == 'Pickaboo'或其他预定义的字符串。 在MATLAB中实现这一点的最佳方法是什么? 显然,对于数组来说这很容易,但如何对单元格进行筛选呢?

3个回答

12
你可以使用CELLFUN来完成这个任务。
hits = cellfun(@(x)strcmp(x.s.text,'Pickabo'),mylist);
filteredList = mylist(hits);

然而,为什么要创建一个结构体的单元格?如果你的结构体都有相同的字段,你可以创建一个结构体数组。要获取命中次数,则需要使用ARRAYFUN


4

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

mylist = [mylist{:}];

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

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

在这里,isMatch将是一个与mylist长度相同的逻辑索引向量,其中匹配到的位置为1,否则为0。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接