Finding and filtering elements in a MATLAB cell array

smichak picture smichak · Aug 11, 2010 · Viewed 17.9k times · Source

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 predefined 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?

Answer

Jonas picture Jonas · Aug 11, 2010

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.