필터 지우기
필터 지우기

How to access the Nth element of 1x1 struct with 5 fields?

조회 수: 31 (최근 30일)
Hasan Kaan Tuna
Hasan Kaan Tuna 2023년 7월 28일
댓글: Stephen23 2023년 7월 28일
Hi,
I have a 1x1 struct with 5 fields defined in workspace. Also, in that struct there are two collumns as "field" and "value". How can I access the name of Nth element of that struct?
When I try,
struct(n)
Matlab gives me following error:
Index exceeds matrix dimensions.
Thank you for your help.
  댓글 수: 2
Stephen23
Stephen23 2023년 7월 28일
편집: Stephen23 2023년 7월 28일
@Hasan Kaan Tuna: please upload your data in a MAT file by clicking the paperclip button.
"Also, in that struct there are two collumns as "field" and "value"."
You wrote that the structure is 1x1, so it cannot have "two collumns". Most likely you are getting mixed up by how the workspace / variable viewer displays structures, which by default shows the fields as columns (i.e. nothing to do with the structure size). Rather than rely on a contradictory explanation it would be much more reliable to have the original data to work with.
"When I try, struct(n) Matlab gives me following error"
Of course: if a structure only has one element, what do you expect to get when you try to access its non-existent 2nd element? The same applies for any other array type, not just structure arrays.
Dyuman Joshi
Dyuman Joshi 2023년 7월 28일
Do you want to get the field names of the struct? Then use fieldnames.

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

채택된 답변

Pranavkumar Mallela
Pranavkumar Mallela 2023년 7월 28일
편집: Pranavkumar Mallela 2023년 7월 28일
Hi Hasan,
I understand that you want to access the nth field in a struct. As Dyuman indicated, you can use the ''fieldnames" function.
Please find code for the same:
s = struct('field1', 1, 'field2', 2,'field3', 3,'field4', 4,'field5', 5); % your 5-field struct
s_fields = fieldnames(s); % use fieldnames
n=2;
nthfield = s_fields{n}; % accessing the nth field
val = s.(nthfield); % val holds the value of the nth field
For more information regarding the "fieldnames" function,you can refer to the following documentation: https://www.mathworks.com/help/matlab/ref/fieldnames.html
Hope this helps! Thanks!
  댓글 수: 3
Hasan Kaan Tuna
Hasan Kaan Tuna 2023년 7월 28일
Thank you. Who would have guess the curly braces :)
Stephen23
Stephen23 2023년 7월 28일
"Who would have guess the curly braces :)"
No guessing is required with MATLAB: FIELDNAMES returns a cell array, as its documentation clearly states.
Also this data type is shown in the command window:
S = struct('x',1,'y',2);
C = fieldnames(S)
C = 2×1 cell array
{'x'} {'y'}

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by