Find a value in structure
141 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/936499/image.png)
3 comentarios
Vatsal
el 29 de Sept. de 2023
Editada: Vatsal
el 7 de Oct. de 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
el 7 de Oct. de 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);
Respuestas (1)
Voss
el 7 de Oct. de 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 comentarios
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!