MATLAB Answers

Dynamic call to structure elements

7 views (last 30 days)
I intend to use a for loop to process iterative computation on different elements of a structure; my structure is made of:
  • MyStruct.Elmt1
  • MyStruct.Elmt2
  • MyStruct.Elmt3
  • ...
How can I dynamicaly call each element of my structure (incrementing the number : Elmt1, Elmt2,...) in order to use it in a for loop?
Thanks

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 8 Jul 2020
Those are not elements of a structure, those are fields of a structure.
Your example structure has only has one element (because it is scalar) and has multiple fields.
A non-scalar structure has multiple elements, totally independent of how many fields it has.
I recommend revising the basic concepts: https://www.mathworks.com/help/matlab/structures.html

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Jul 2020
for K = 1 : 3
MyStruct.(sprintf('Elmt%d', K))
end
or
for K = 1 : 3
MyStruct.("Elmt"+K) %rely on string objects
end

  0 Comments

Sign in to comment.

More Answers (1)

Stephen Cobeldick
Stephen Cobeldick on 8 Jul 2020
You can trivially access the fields of a structure using this syntax, where F is the fieldname:
S.(F)
You could use sprintf to generate the fieldnames, e,g.:
idx = 1;
fnm = sprintf('Elmt%u',idx);
MyStruct.(fnm)
Note that your code would be simpler and more efficient if you used a non-scalar structure, e.g.:
S(1).Elmt = 1;
S(2).Emlt = 22;
S(3).Emlt = 333;
then you can trivially access any element of that structure array using basic, efficeint indexing:
idx = 1;
S(idx).Emlt

  0 Comments

Sign in to comment.

Products


Release

R2020a

Translated by