Matlab:将值添加到初始化的嵌套struct-cell中 [英] Matlab: adding value into initialized nested struct-cell
问题描述
我有这个结构
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
但是当我想添加一个值
Data.trials{i}.theta = 27;
我收到此错误...
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?
谢谢!
推荐答案
If you take a look at the documentation of struct
, it says the following statement:
s = struct(field,value)
使用指定的字段和值创建一个结构数组.
s = struct(field,value)
creates a structure array with the specified field and values.
...
...
- 如果任何
value
输入是一个空单元格数组{},则输出s是一个空(0×0)结构.
- If any
value
input is an empty cell array, {}, then output s is an empty (0-by-0) structure.
因为您的字段已初始化为{}
,所以它们是空单元格数组,因此您将获得一个空结构,因此您无法访问该结构,因为它是空的.如果要初始化struct
,请使用空括号代替[]
.换句话说,在您的for
循环中,执行以下操作:
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
这应该为您正确初始化结构,然后您可以相应地访问字段.因此,如果我想在单元格数组的第一个结构中初始化theta
:
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
这篇关于Matlab:将值添加到初始化的嵌套struct-cell中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!