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]
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 个评论
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!