Clear Filters
Clear Filters

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

31 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 28 Jul 2023
Edited: Stephen23 on 28 Jul 2023
@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.

Sign in to comment.

Accepted Answer

Pranavkumar Mallela
Pranavkumar Mallela on 28 Jul 2023
Edited: Pranavkumar Mallela on 28 Jul 2023
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 Comments
Stephen23
Stephen23 on 28 Jul 2023
"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'}

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!