How do I use logical indexing on an array made up of structs that contain character fields?

15 views (last 30 days)
I have a structure with two fields, type and specie, both of which contain character strings. I built an array consisting of only these structures, and now I'm trying to use logical indexing to find the elements of a given type. The code is as follows:
A(1).type = 'insect';
A(1).specie = 'fly';
A(2).type = 'insect';
A(2).specie = 'moth';
A(3).type = 'fish';
A(3).specie = 'grouper';
A(4).type = 'fish';
A(4).specie = 'tuna';
[A([A.type] == 'insect').specie]
I'm modifying the solution to this question, but I get an error that says:
Error using ==
Matrix dimensions must agree.
Error in myfile (line 12)
[A([A.type] == 'insect').specie]
I know that comparing strings with == isn't good, so I thought I would use strcmp instead. However, this code:
[A([strcmp(A.type, 'insect')]).specie]
produces an error of
Error using strcmp
Too many input arguments.
Error in myfile (line 12)
[A([strcmp(A.type, 'insect')]).specie]
If I use an anonymous function, I can create an array of structures that meet the criterion, i.e.
hits = A(arrayfun(@(x)strcmp(x.type, 'insect'), A));
but I don't know how to get the fields from those structures into another array without resorting to a loop.
How can I perform this task using the base Matlab only?

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 4 Feb 2013
Edited: Azzi Abdelmalek on 4 Feb 2013
x={A.type}
A(strcmp(x, 'insect')).specie

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!