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

8 次查看(过去 30 天)
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?

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2013-2-4
编辑:Azzi Abdelmalek 2013-2-4
x={A.type}
A(strcmp(x, 'insect')).specie

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by