Accessing values of fieldnames in a structure without using the fieldnames function

17 vues (au cours des 30 derniers jours)
Hi all,
I've got a structure which has 20 different field names, e.g. 'fieldname01','fieldname02' etc.
Each fieldname has a numeric value, such as:
fieldname01: 0.56 fieldname02: 0.93 fieldname03: -0.34
Up to fieldname20
I need to access the numeric values of certain field names, for example the 2nd, 5th and 15th. Just wondering what would be the right way about doing this without using the fieldnames function if that's possible at all?
Thank you.

Réponse acceptée

Sven
Sven le 4 Avr 2013
Modifié(e) : Sven le 4 Avr 2013
Hi Jess,
Use parentheses:
S = struct('field1',1,'field2',2)
fieldStr = ['fields' num2str(1)]
S.(fieldStr)
ans =
1
Or, with your particular example:
for i = 1:20
val = S.(sprintf('fieldname%02d',i))
end
Please note however that the "right" way to store data from 1 to 20 isn't in a structure with the number built into the name. Instead it sounds like you should be using an array (or cell array if your datatypes are different).
For example:
myData = [12 10 3];
is much cleaner than:
myData.element1 = 12
myData.element2 = 10
myData.element3 = 3
  2 commentaires
Jan
Jan le 4 Avr 2013
+1 for mentioning, that an enumeration of fieldnames is much worse than using arrays.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by