Trouble with struct indexing?

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by