Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 949
Sean Avatar asked Feb 18 '11 17:02

Sean


People also ask

How do you access structure data in Matlab?

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.

How do I extract a field from a structure in Matlab?

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.

How do you convert a struct to an array in Matlab?

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.

How do you convert a struct to a table?

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.


1 Answers

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.

like image 114
gnovice Avatar answered Sep 21 '22 02:09

gnovice