Dynamic call to structure elements

조회 수: 19 (최근 30일)
Tom Dollfus
Tom Dollfus 2020년 7월 8일
이동: Stephen23 2023년 12월 8일
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
Stephen23
Stephen23 2020년 7월 8일
이동: Stephen23 2023년 12월 8일
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

댓글을 달려면 로그인하십시오.

채택된 답변

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by