How to access data in structures?

조회 수: 106 (최근 30일)
Brett Baxter
Brett Baxter 2020년 10월 17일
댓글: Stephen23 2020년 10월 17일
I'm currently learning how to use structures in MATLAB and I'm finding it a little more confusing than cells and other regular arrays. I'm confused on how to call data stored in specific fields of a structure. I understand the format is "nameofstructure"."nameoffield", but I'm struggling with how to get the data I need from the structure without knowing the name of the fields. Say I had a structure with 2 fields, how would I go about getting the infomation from either one without knowing the name of the field? I tried pulling the names of the fields in a function and using them like so
fieldnames = fieldnames(structure)
fieldInedd = fieldnames(2)
informationfromthisfield = structure.fieldIneed
But this doesn't give a field that matlab can recognize and draw data from. Could anyone help?
  댓글 수: 1
Stephen23
Stephen23 2020년 10월 17일
To access the structure fieldname dynamically you need the syntax given here:
and to access the contents of the cell array returned by fieldnames you need to use curly braces:

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

채택된 답변

Walter Roberson
Walter Roberson 2020년 10월 17일
fieldnames = fieldnames(structure)
fieldInedd = fieldnames{2}
informationfromthisfield = structure.(fieldIneed)
Notice the () around the field name: it is important. This syntax is "dynamic field names".
This syntax of dot followed by a variable name or expression in () is also used for referencing table variables that are not valid MATLAB variable names.
  댓글 수: 1
Brett Baxter
Brett Baxter 2020년 10월 17일
Got it, this works for me. Thank you!

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

추가 답변 (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