Trouble with struct indexing?

3 Ansichten (letzte 30 Tage)
Daniel Montgomery
Daniel Montgomery am 1 Jun. 2020
Kommentiert: Walter Roberson am 2 Jun. 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?

Antworten (2)

Walter Roberson
Walter Roberson am 1 Jun. 2020

Matt J
Matt J am 1 Jun. 2020
Bearbeitet: Matt J am 1 Jun. 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 Kommentar
Walter Roberson
Walter Roberson am 2 Jun. 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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by