Borrar filtros
Borrar filtros

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

31 visualizaciones (últimos 30 días)
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 comentarios
Stephen23
Stephen23 el 28 de Jul. de 2023
Editada: Stephen23 el 28 de Jul. de 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 el 28 de Jul. de 2023
Do you want to get the field names of the struct? Then use fieldnames.

Iniciar sesión para comentar.

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by