String compare in Struct (Matlab)

China☆狼群 提交于 2020-01-25 10:30:06

问题


I need search a large struct and find the index of all the components with the same name.

For example: If the name is 13hy I need an array [1,5] returned

 structure(1,1).name = '13hy'
 structure(2,1).name = '64hy'
 structure(3,1).name = '37hy'
 structure(4,1).name = '07hy'
 structure(5,1).name = '13hy'

I have tried:

 strcmp(structure.name,'13hy')
 ismember(structure.name,'13hy')
 strfind(structure.name,'13hy')

and I keep getting the error 'Too many input arguments.' Please help


回答1:


Use arrayfun to traverse the structure, using a strcmp-based anonymous function to test for the desired name:

find(arrayfun(@(n) strcmp(structure(n).name, '13hy'), 1:numel(structure)))



回答2:


Use []:
strcmp([structure.name],'13hy')

It chains the content and allows you to compre and use the struct very much like a usual variable.

Enjoy!



来源:https://stackoverflow.com/questions/24964753/string-compare-in-struct-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!