Trouble with struct indexing?

3 visualizaciones (últimos 30 días)
Daniel Montgomery
Daniel Montgomery el 1 de Jun. de 2020
Comentada: Walter Roberson el 2 de Jun. de 2020
I have a struct with multiple fields that looks similar to this
Row field field2
1 ### ###
2 ### ###
3 ### ###
...
2000 ### ###
I get an error message when I type matrix.field{b} to access a single element of field2
in a loop for b=100, what is the correct notation to access a signle struct element in a loop?

Respuestas (2)

Walter Roberson
Walter Roberson el 1 de Jun. de 2020

Matt J
Matt J el 1 de Jun. de 2020
Editada: Matt J el 1 de Jun. de 2020
... to access a single element of field2.
The layout of your struct variable is not clear. If, for example, you have a scalar struct of the following form,
matrix.Row=1:3;
matrix.field1=4:6;
matrix.field2={4,5,6};
then this is the notation that you would use to extract the third element of field2,
>> b=3; matrix.field2{b}
ans =
6
This does not work for field1, because the contents of field1 is not a cell array,
>> b=3; matrix.field1{b}
Brace indexing is not supported for variables of this type.
However, ()-indexing will work as desired,
>> b=3; matrix.field1(b)
ans =
6
  1 comentario
Walter Roberson
Walter Roberson el 2 de Jun. de 2020
I believe that they were hoping that
b=2;
matrix.field{b}
would access matrix.field2
but it is not completely clear. Possibly they have a nonscalar structure and were looking for matrix(b).field2

Iniciar sesión para comentar.

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by