How to access a field of a struct by indexing?

조회 수: 287 (최근 30일)
Rightia Rollmann
Rightia Rollmann 2017년 2월 26일
댓글: Voss 2023년 12월 19일
I have a 1-by-1 struct that possesses 3 fields named B, C, and D. Is there any way to call D by its index (i.e., D is the third field of struct A, so call the third field of struct A without mentioning the field name D) rather than its name (i.e, A.D)?
A.B = 1;
A.C = 2;
A.D = 3;
  댓글 수: 1
Stephen23
Stephen23 2017년 2월 26일
편집: Stephen23 2017년 2월 26일
@Rightia Rollmann: you might like to consider using a non-scalar structure, which lets you use indexing to access structures:

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

채택된 답변

Jan
Jan 2017년 2월 26일
편집: Jan 2017년 2월 26일
A_cell = struct2cell(A);
D = A_cell{3}
Keep in mind that the order of the fields of structs is not necessarily constant:
A.B = 1;
A.C = 2;
A.D = 3;
B.B = 1;
B.D = 3;
B.C = 2;
isequal(A, B) % >> TRUE!
  댓글 수: 4
Richard Crozier
Richard Crozier 2019년 8월 1일
If struct2cell results in copying the data in the structure, Guillaume's answer below is superior.
James Tursa
James Tursa 2019년 8월 1일
struct2cell creates shared-data-copies of the field variables. So, while there is overhead involved in creating the variable header info, the data itself is not copied.

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

추가 답변 (1개)

Guillaume
Guillaume 2017년 2월 26일
Yes, there is a way to get the nth field directly:
fns = fieldnames(A);
A.(fns{3})
But be aware that the order of the fields depends solely on the order in which they were created. As Jan pointed out, two structures may be indentical, yet have different field order.
Usually, you would only access fields by their index when you're doing some structure metaprogramming
  댓글 수: 5
Vaishnavi
Vaishnavi 2023년 12월 19일
To add on to this question, can someone explain why A.(subsref(fieldnames(A),substruct('{}',{:}))) would not work?
Voss
Voss 2023년 12월 19일
@Vaishnavi: One reason that doesn't work is that you need single quotes around the colon in substruct. But even then, it may not do what you expect. Here's what it does (gets the value of the first field of A):
A = struct('field1',1,'field2',2)
A = struct with fields:
field1: 1 field2: 2
A.(subsref(fieldnames(A),substruct('{}',{':'})))
ans = 1
In order to know whether that "works", one would need to know what you expected it to do.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by