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
Structures store data in containers called fields, which you can then access by the names you specify. Use dot notation to create, assign, and access data in structure fields. If the value stored in a field is an array, then you can use array indexing to access elements of the array.
Extract Fields From Structurehold on plot(extractfield(roads,'X'),extractfield(roads,'Y')); plot(extractfield(r,'X'),extractfield(r,'Y'),'m'); Extract the names of the roads, stored in the field STREETNAME . The field values are character vectors, so the result is returned in a cell array.
C = struct2cell( S ) converts a structure into a cell array. The cell array C contains values copied from the fields of S . The struct2cell function does not return field names. To return the field names in a cell array, use the fieldnames function.
T = struct2table( S ) converts the structure array, S , to a table, T . Each field of S becomes a variable in T . T = struct2table( S , Name,Value ) creates a table from a structure array, S , with additional options specified by one or more Name,Value pair arguments.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With