How do I use logical indexing on an array made up of structs that contain character fields?
16 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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]
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?
0 Commenti
Risposta accettata
Azzi Abdelmalek
il 4 Feb 2013
Modificato: Azzi Abdelmalek
il 4 Feb 2013
x={A.type}
A(strcmp(x, 'insect')).specie
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!