对于我的代码,我需要一个可变的结构。根据计数器,结构应添加其他字段。所有字段都应灵活,可能具有不同的值。目前,我使用switch
条件。为了透明,我想改变这一点。举个例子,我的代码可以为(spl{1,i}{1})
采用不同的值(例如输入/输出,......)。后一个数字(1
)计算到达structlength
。因此,如果structlength
等于2
,代码将如下所示:testData.(spl{1,i}{1}).(spl{1,i}{2})
总结:是否可以消除开关状况?
switch structLength
case 1
testData.(spl{1,i}{1}) = emptyMat;
case 2
testData.(spl{1,i}{1}).(spl{1,i}{2}) = emptyMat;
case 3
testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3}) = emptyMat;
case 4
testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3})...
.(spl{1,i}{4}) = emptyMat;
case 5
testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3})...
.(spl{1,i}{4}).(spl{1,i}{5}) = emptyMat;
case 6
testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3})...
.(spl{1,i}{4}).(spl{1,i}{5}).(spl{1,i}{6}) = emptyMat;
switch
可以用for
循环(没有eval
)替换如下。但我建议您选择更简单的数据结构,这将使您的生活更轻松。
% Example data
emptyMat = [10 22];
structLength = 3;
spl = {{'a', 'bb', 'ccc'}};
ii = 1;
% Create the nested struct
testData = emptyMat; % Result so far. Will be wrapped into fields from inner to outer
for k = structLength:-1:1
testData = struct(spl{1,ii}{k}, testData); % wrap into an outer field
end
校验:
>> testData
testData =
struct with fields:
a: [1×1 struct]
>> testData.a
ans =
struct with fields:
bb: [1×1 struct]
>> testData.a.bb
ans =
struct with fields:
ccc: [10 22]
>> testData.a.bb.ccc
ans =
10 22