2010-08-11 41 views
9

我有一個列表中的元素(單元陣列)與結構是這樣的:查找和過濾元件

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

現在我想所有結構從中s.text =過濾MYLIST ='Pickaboo'或其他預定義的字符串。在MATLAB中實現這個最好的方法是什麼?顯然這對於​​數組來說很簡單,但是對於單元格來說,最好的方法是什麼?

回答

12

您可以使用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 
4

如果你所有的單元陣列中的結構具有相同的字段('x''y''s'),那麼你可以存儲mylist作爲一個結構數組,而不是一個單元陣列。你可以轉換mylist像這樣:現在

mylist = [mylist{:}]; 

,如果您的所有領域's'還包含與他們相同的字段結構,你可以以同樣的方式收集它們放在一起,然後用STRCMP檢查你的領域'text'

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

這裏,isMatch將是一個logical index vector相同的長度mylist與在發現匹配的1和0,否則。