Trouble with struct indexing?

3 vues (au cours des 30 derniers jours)
Daniel Montgomery
Daniel Montgomery le 1 Juin 2020
Commenté : Walter Roberson le 2 Juin 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?

Réponses (2)

Walter Roberson
Walter Roberson le 1 Juin 2020

Matt J
Matt J le 1 Juin 2020
Modifié(e) : Matt J le 1 Juin 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 commentaire
Walter Roberson
Walter Roberson le 2 Juin 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by