Filter löschen
Filter löschen

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

31 Ansichten (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 28 Jul. 2023
Bearbeitet: Stephen23 am 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.
Dyuman Joshi
Dyuman Joshi am 28 Jul. 2023
Do you want to get the field names of the struct? Then use fieldnames.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Pranavkumar Mallela
Pranavkumar Mallela am 28 Jul. 2023
Bearbeitet: Pranavkumar Mallela am 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 Kommentare
Hasan Kaan Tuna
Hasan Kaan Tuna am 28 Jul. 2023
Thank you. Who would have guess the curly braces :)
Stephen23
Stephen23 am 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'}

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by