Find a value in structure
170 views (last 30 days)
Show older comments
The answer below that question is.
valuetofind = 58;
find(arrayfun(@(s) ismember(valuetofind, s.cluster), clusters))
But if I want to find one value in different fields?
e.g. 18841 maybe in e1||e2||e3 ,and I want to return the index 4
3 Comments
Vatsal
on 29 Sep 2023
Edited: Vatsal
on 7 Oct 2023
I understand that you want to find a value in different fields of a structure and if the value exists, the index should be returned. As Arif Hoq mentioned, you can do that with the “ismember” function. I am attaching the code below to find a value in the different fields of a structure and to return the index of the value:
yourStruct = struct('e1',{1 2 3 18841},'e2',{1 2 18841 4},'e3',{1 2 3 4});
valueToFind = 18841;
fieldsToSearch = {'e1', 'e2', 'e3'}; % Specify the fields to search
index = find(arrayfun(@(s) any(ismember(valueToFind, s.(fieldsToSearch{1}))) || ...
any(ismember(valueToFind, s.(fieldsToSearch{2}))) || ...
any(ismember(valueToFind, s.(fieldsToSearch{3}))), yourStruct), 1);
You can also refer to the MATLAB documentation for the functions used in the above code to obtain more information on its usage and syntax. The links are provided below: -
I hope this helps!
Voss
on 7 Oct 2023
@Vatsal: You can't dynamically reference multiple fields of a struct using a cell array of field names:
yourStruct = struct('e1',{1 2 3 18841},'e2',{1 2 18841 4},'e3',{1 2 3 4})
valueToFind = 18841;
fieldsToSearch = {'e1', 'e2', 'e3'}; % Specify the fields to search
index = find(arrayfun(@(s) any(ismember(valueToFind, s.(fieldsToSearch))), yourStruct), 1);
Answers (1)
Voss
on 7 Oct 2023
yourStruct = struct('e1',{1 2 3 18841},'e2',{1 2 18841 4},'e3',{1 2 3 4})
valueToFind = 18841;
fieldsToSearch = {'e1', 'e2', 'e3'}; % Specify the fields to search
index = cellfun(@(f) find([yourStruct.(f)] == valueToFind, 1), fieldsToSearch, 'UniformOutput', false)
Here index gives you the index of the element of yourStruct that contains the first instance of valueToFind in each field in fieldsToSearch. E.g., in this case index tells you that 18841 appears as yourStruct(4).e1, yourStruct(3).e2, and doesn't appear in [yourStruct.e3] at all.
yourStruct(4).e1
yourStruct(3).e2
[yourStruct.e3]
You can do further processing on index to, say, get the index of the first instance of valueToFind in any searched field of yourStruct, and which field it appeared in:
index(~cellfun(@isscalar,index)) = {Inf}
[min_index,field_index] = min([index{:}])
found_field = fieldsToSearch{field_index}
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!