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 more 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:
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
anda2: 4
, the second array element containsa1: 2
anda2: 5
, and the third array element containsa1: 3
anda2: 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:Then your original
a.a1{1}
will work.EDIT:
If you create your structure using numeric arrays instead of cell arrays, like so:
Then you can access the value of 1 as follows:
For further information about working with structures in MATLAB, check out this documentation page.