Matlab: adding value into initialized nested struct-cell

 ̄綄美尐妖づ 提交于 2019-11-30 17:33:54

问题


I have this structure

Data = struct('trials',{},'time',{},'theta_des',{},'vel_des',{},'trials_number',{},'sample_numbers',{});
Data(1).trials = cell(1,trials_number);
for i=1:trials_number
   Data.trials{i} = struct('theta',{},'pos_err',{},'vel',{},'vel_err',{},'f_uparm',{},'f_forearm',{},'m_uparm',{},'m_forearm',{},...
                           'current',{},'total_current',{},'control_output',{},'feedback',{},'feedforward',{},'kp',{});
end

but when I want to add a value

Data.trials{i}.theta = 27;

I get this error...

A dot name structure assignment is illegal when the structure is empty.  Use a subscript on the structure.

Any idea of how to solve it?

Thanks!


回答1:


If you take a look at the documentation of struct, it says the following statement:

s = struct(field,value) creates a structure array with the specified field and values.

...

...

  • If any value input is an empty cell array, {}, then output s is an empty (0-by-0) structure.

Because your fields are initialized to {}, these are empty cell arrays, you will get an empty structure, so you are not able to access into the structure as it's empty. If you want to initialize the struct, use the empty braces instead []. In other words, in your for loop, do this:

for i=1:trials_number
    Data.trials{i} = struct('theta',[],'pos_err',[],'vel',[],'vel_err',[],'f_uparm',[],'f_forearm' [],'m_uparm',[],'m_forearm',[],...
    'current',[],'total_current',[],'control_output',[],'feedback',[],'feedforward',[],'kp',[]);
end

This should properly initialize the structure for you, and you can then access the fields accordingly. As such, if I wanted to initialize theta in the first structure within your cell array:

Data.trials{1}.theta = 27;

This will now work. You can verify the output by:

disp(Data.trials{1}.theta)

27


来源:https://stackoverflow.com/questions/25998644/matlab-adding-value-into-initialized-nested-struct-cell

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