2010-08-11 18 views
9

मैं एक सूची तत्वों के (सेल सरणी) structs के साथ इस तरह है:ढूँढना और छानने तत्वों

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

अब मैं सब structs के लिए है जहाँ से s.text = MyList फ़िल्टर करना चाहते हैं = 'पिकबू' या कुछ अन्य पूर्वनिर्धारित स्ट्रिंग। MATLAB में इसे प्राप्त करने का सबसे अच्छा तरीका क्या है? स्पष्ट रूप से यह सरणी के लिए आसान है, लेकिन कोशिकाओं के लिए ऐसा करने का सबसे अच्छा तरीका क्या है?

उत्तर

12

आप इसके लिए CELLFUN का उपयोग कर सकते हैं।

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

हालांकि, आप structs का एक सेल क्यों बनाते हैं? यदि आपके structs में सभी एक ही फ़ील्ड हैं, तो आप structs की सरणी बना सकते हैं। हिट पाने के लिए, आप 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

अपने सेल सरणी में अपनी संरचनाओं के सभी तो आप एक संरचना सरणी के बजाय एक सेल सरणी के रूप में mylist स्टोर कर सकते हैं एक ही क्षेत्र ('x', 'y', और 's') है। तुम इतनी तरह mylist परिवर्तित कर सकते हैं:

mylist = [mylist{:}]; 

अब, अगर आपके सभी क्षेत्रों 's' भी उन्हें में एक ही क्षेत्रों के साथ संरचनाओं के होते हैं, आप उन सब को एक साथ एक ही तरीके से, एकत्र कर सकते हैं तो STRCMP का उपयोग कर अपने क्षेत्र 'text' की जाँच करें:

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

यहाँ, isMatch हैं जहां मिलान हो जाता है और शून्य अन्यथा साथ mylist के रूप में एक logical index vector एक ही लंबाई हो जाएगा।

संबंधित मुद्दे