在 MATLAB 元胞数组中查找和过滤元素

Posted

技术标签:

【中文标题】在 MATLAB 元胞数组中查找和过滤元素【英文标题】:Finding and filtering elements in a MATLAB cell array 【发布时间】: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 中实现这一目标的最佳方法是什么?显然这对于​​数组来说很容易,但是对于单元格来说最好的方法是什么?

【问题讨论】:

【参考方案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,其中找到匹配项,否则为零。

【讨论】:

以上是关于在 MATLAB 元胞数组中查找和过滤元素的主要内容,如果未能解决你的问题,请参考以下文章

关于MATLAB cell元胞数组中元素的引用问题

matlab中怎么查找一个数组中所有的非零元素的位置

matlab怎样合并元胞数组

MATLAB的cell数组

matlab中的元胞数组如何实现批量的赋值呢?

Matlab中数组元素为矩阵怎样表示