views:

109

answers:

3

Hi,

I have a list (cell array) of elements with structs like this:

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

Now I would like to filter mylist for all structs from which s.text == 'Pickaboo' or some other predefines string. What is the best way to achieve this in matlab? Obviously this is easy for arrays, but what is the best way to do this for cells?

+2  A: 

You can use CELLFUN for this.

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

However, why do you make a cell of structs? If your structs all have the same fields, you can make an array of structs. To get the hits, you'd then use ARRAYFUN.

Jonas
A: 

Use 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
YYC
+1  A: 

If all of your structures in your cell array have the same fields ('x', 'y', and 's') then you can store mylist as a structure array instead of a cell array. You can convert mylist like so:

mylist = [mylist{:}];

Now, if all your fields 's' also contain structures with the same fields in them, you can collect them all together in the same way, then check your field 'text' using STRCMP:

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

Here, isMatch will be a logical index vector the same length as mylist with ones where a match is found and zeroes otherwise.

gnovice

related questions