为什么setfield会覆盖以前的结构?

时间:2013-11-13 08:37:29

标签: matlab structure

我对MATLAB很陌生,我在构建一个可以用另一个m文件迭代的结构时遇到了问题。我有i个受试者,他们在每次试验中都进行tw段试验。我现在想要存储每个段的特定时间点。这里称为startTimestopTime。我尝试了以下(一个主题,一个试验):

i=1; %Testperson #


% Trial 1
t=1; %Trial #

w=1; %Segment 1

selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'startTime',0.001*5000)
selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'stopTime',24.5*5000)

w=2; %Segment 2

selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'startTime',0.001*5000);
selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'stopTime',24.5*5000);

w=3; %Segment 3

selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'startTime',0.001*5000);
selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'stopTime',24.5*5000);

w=4; %Segment 4

selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'startTime',0.001*5000);
selectedData = setfield('selectedData',['Subj' num2str(i)],['Trial' num2str(t)],{w},'stopTime',24.5*5000);

似乎setfield会覆盖我想要存储的先前值?有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如果上面的代码真的是你正在执行的,我有点惊讶它实际上有效。

setfield的第一个参数应该是您想要更改的结构,而不是它作为字符串的名称。 所以试试:

selectedData = setfield(selectedData,['Subj' num2str(i)],['Trial' num2str(t)],{w},'startTime',0.001*5000);
selectedData = setfield(selectedData,['Subj' num2str(i)],['Trial' num2str(t)],{w},'stopTime',24.5*5000);

<强>可是: 这看起来像一个设计不太好的结构。当你也可以使用适当的索引时,你不应该使用“枚举”字段名作为索引。

在你的情况下,你应该使用结构数组,例如像这样:

subjects(i).trials(t).startTime(w) = xx;
subjects(i).trials(t).stopTime(w) = yy;

这使得事情a)更容易编码,b)允许以后更容易访问数据。