access struct data (matlab)
a= struct('a1',{1,2,3},'a2',{4,5,6})
how can Iget the value of 1;
I try to use a.a1{1} which return errors
>> a.a1{1}
??? Field reference for multiple structure elements that is followed by mo开发者_运维百科re reference blocks is an
error.
How can I access 1? Thanks.
Edit
A = struct{'a1',[1 2 3],'a2',[4 5 6]}
How can I access 1. I use A(1).a1
but I get 1 2 3
You have to do this instead:
a(1).a1
The reason why is because the code you use to create your structure actually creates a 3-element structure array where the first array element contains a1: 1
and a2: 4
, the second array element contains a1: 2
and a2: 5
, and the third array element contains a1: 3
and a2: 6
.
When you use curly braces {}
in a call to STRUCT like you did, MATLAB assumes you are wanting to create a structure array in which you distribute the contents of the cells across the structure array elements. If you instead want to create a single 1-by-1 structure element where the fields contain cell arrays, you have to add an additional set of curly braces enclosing your cell arrays, like so:
a = struct('a1',{{1,2,3}},'a2',{{4,5,6}});
Then your original a.a1{1}
will work.
EDIT:
If you create your structure using numeric arrays instead of cell arrays, like so:
A = struct('a1',[1 2 3],'a2',[4 5 6]);
Then you can access the value of 1 as follows:
A.a1(1)
For further information about working with structures in MATLAB, check out this documentation page.
精彩评论