access struct data (matlab)

佐手、 提交于 2019-12-01 17:01:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/5044452/access-struct-data-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!