Trouble with struct indexing?

1 回表示 (過去 30 日間)
Daniel Montgomery
Daniel Montgomery 2020 年 6 月 1 日
コメント済み: Walter Roberson 2020 年 6 月 2 日
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?

回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 6 月 1 日

Matt J
Matt J 2020 年 6 月 1 日
編集済み: Matt J 2020 年 6 月 1 日
... 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 件のコメント
Walter Roberson
Walter Roberson 2020 年 6 月 2 日
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

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by