Hi all,
I have a structure, which includes a nested structure.
It looks like this:
obj.characteristic1 = 'Test';
obj.characteristic2 = 'Test2';
obj.characteristic3 = 30;
obj.characteristic4 = struct('Name', [],...
'Age', [],...
'Height', [],...
'Gender', []);
The nested structure has 30 entries.
Target is to find a defined name, e.g. 'Tim'.
obj.characteristic4(1).name = 'Mike'
obj.characteristic4(2).name = 'Tim'
obj.characteristic4(3).name = 'David'
obj.characteristic4(4).name = 'Chris'
My solution on finding the index currently looks like this and is working.
fori=1:1:obj.characteristic3
if strcmp(obj.characteristic4(i).name,'Tim')
nameIndex = i;
end
end
The question is, whether there is a smarter way without a for-loop to find the index of the name field with the matching string.
Thank you for your help.

1 commentaire

Stephen23
Stephen23 le 12 Mar 2020
Modifié(e) : Stephen23 le 12 Mar 2020
"...is a smarter way without a for-loop to find the index of the name field with the matching string"
As long as the parent structure is scalar, you can use a comma-separated list:
See Walter Roberson's answer for an example.

Connectez-vous pour commenter.

 Réponse acceptée

Walter Roberson
Walter Roberson le 12 Mar 2020
Modifié(e) : Walter Roberson le 12 Mar 2020
In the case where the name might occur multiple times and you want to locate all of them, and you are only searching for one name:
idx = find(ismember({obj.characteristic4.name}, NameToSearchFor))
idx could be empty if the name is not found
In the case where the name occurs at most once or you only care about the first of them
[wasfound, idx] = ismember(NameToSearchFor, ismember({obj.characteristic4.name})
wasfound will be true if the name was found. idx will be the corresponding index in obj.characteristic4
In both cases you can extend NameToSearchFor to a cell array of character vectors of names to look for. With one order of the arguments to ismember, you are looking to see whether each name like 'Tim' matches somewhere in the characteristic4 list, and with the other order of arguments to ismember, you are looking to see whether the entries in the characteristic4 list match something in the list of names. Both have their uses.

3 commentaires

Thank you for the help.
This is working fine when I adjust your code a little.
[wasfound, idx] = ismember(NameToSearchFor, ismember({obj.characteristic4.name})
The second 'ismember' is too much.
So the solution is:
[wasfound, idx] = ismember(NameToSearchFor, {obj.characteristic4.name})
Walter Roberson
Walter Roberson le 15 Mar 2020
Ah, not sure how I made that typing mistake.
Vamsi
Vamsi le 27 Juil 2023
how to find matching value index of structure member values

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by