# How to access a field of a struct by indexing?

2,808 ビュー (過去 30 日間)
Rightia Rollmann 2017 年 2 月 26 日

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 2017 年 2 月 26 日

@Rightia Rollmann: you might like to consider using a non-scalar structure, which lets you use indexing to access structures:

サインインしてコメントする。

### 採用された回答

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 件のコメント表示非表示 3 件の古いコメント
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 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
##### 3 件のコメント表示非表示 2 件の古いコメント
James Richard 2019 年 12 月 14 日

@Guillaume, how do you make it shorter, one line only?
I mean something like this
A.(fieldnames(A){3}) % it doesn't work
%Error:
%Indexing with parentheses '()' must appear as the last operation of a valid indexing expression.
Edit, I found the solution from stackoverflow
A.(subsref(fieldnames(A),substruct('{}',{3})))

サインインしてコメントする。

### カテゴリ

Find more on Structures in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by