say I have a large structure with lots of names (eg 'a', 'b', etc). Given a name and without knowing the index of that particular name, I would like to find that name, similar to the find() command so that I can write additional fields to it
dat.name = 'a'
dat(2).name = 'b'
...
dat(26).name = 'z'
dat.name == 'a'
% MATLAB error
Error using ==
Too many input arguments.
If I undersand corretly, you want to find an index/indexes in struct array for which name field has given value? If yes, you can do as follows:
indexes = find(strcmp({dat(:).name}, 'a'))
To get the list of fields in a struct (as a cell array of strings), use:
fields(myStruct)
To access the value of a field where the name of the field is held in a variable (as a string), use:
myStruct.(fieldName)
If all your strings are one-character, you can use
>> find([dat.name] == 'b') %// concat into a single string (character vector)
ans =
2
If the strings may have any number of characters:
>> [temp{1:numel(dat)}] = deal(dat.name); %// build a cell array of strings
>> find(strcmp(temp,'b'))
ans =
2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.